Questions tagged [c#]

C# (pronounced "see sharp") is a high-level, statically typed, multi-paradigm programming language developed by Microsoft. C# code usually targets Microsoft's .NET family of tools and run-times, which include .NET, .NET Framework, .NET MAUI, and Xamarin among others. Use this tag for questions about code written in C# or about C#'s formal specification.

Filter by
Sorted by
Tagged with
1870 votes
26 answers
2.1m views

What is a NullReferenceException, and how do I fix it?

I have some code and when it executes, it throws a NullReferenceException, saying: Object reference not set to an instance of an object. What does this mean, and what can I do to fix this error?
227 votes
5 answers
327k views

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

I have some code and when it executes, it throws a IndexOutOfRangeException, saying, Index was outside the bounds of the array. What does this mean, and what can I do about it? Depending on ...
Adriano Repetti's user avatar
838 votes
15 answers
245k views

Random number generator only generating one random number

I have the following function: //Function to get random number public static int RandomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); } How I call it: ...
Ivan Prodanov's user avatar
1577 votes
47 answers
823k views

How do I update the GUI from another thread?

Which is the simplest way to update a Label from another Thread? I have a Form running on thread1, and from that I'm starting another thread (thread2). While thread2 is processing some files I would ...
CruelIO's user avatar
  • 18.2k
1280 votes
9 answers
353k views

How do I call a generic method using a Type variable?

What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime? Consider the following sample code - inside the ...
Bevan's user avatar
  • 43.6k
83 votes
2 answers
14k views

Post an HTML Table to ADO.NET DataTable

I have a HTML table as below in my View: <table id="tblCurrentYear"> <tr> <td>Leave Type</td> <td>Leave Taken</td> <td>Leave ...
RKh's user avatar
  • 13.8k
280 votes
10 answers
73k views

Captured variable in a loop in C#

I met an interesting issue about C#. I have code like below. List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add(() =&...
Morgan Cheng's user avatar
  • 74.1k
671 votes
22 answers
496k views

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

I have a scenario. (Windows Forms, C#, .NET) There is a main form which hosts some user control. The user control does some heavy data operation, such that if I directly call the UserControl_Load ...
Prerak K's user avatar
  • 11k
2613 votes
59 answers
998k views

Deep cloning objects

I want to do something like: MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); And then make changes to the new object that are not reflected in the ...
NakedBrunch's user avatar
  • 48.7k
1621 votes
53 answers
1.2m views

How do you convert a byte array to a hexadecimal string, and vice versa?

How can you convert a byte array to a hexadecimal string and vice versa?
1108 votes
31 answers
652k views

Randomize a List<T>

What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type ...
mirezus's user avatar
  • 13.9k
557 votes
17 answers
1.4m views

How can I deserialize JSON with C#?

I have the following code: var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent); The input in responsecontent is JSON, but it is not properly deserialized into ...
user avatar
144 votes
10 answers
273k views

Serialize and Deserialize Json and Json Array in Unity

I have a list of items send from a PHP file to unity using WWW. The WWW.text looks like: [ { "playerId": "1", "playerLoc": "Powai" }, { "playerId": "2", "...
dil33pm's user avatar
  • 1,613
804 votes
43 answers
346k views

How do I properly clean up Excel interop objects?

I'm using the Excel interop in C# (ApplicationClass) and have placed the following code in my finally clause: while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { } ...
HAdes's user avatar
  • 16.7k
553 votes
16 answers
104k views

Why are mutable structs “evil”?

Following the discussions here on SO I already read several times the remark that mutable structs are “evil” (like in the answer to this question). What's the actual problem with mutability and ...
Dirk Vollmar's user avatar
1510 votes
33 answers
678k views

What is the difference between a field and a property?

In C#, what makes a field different from a property, and when should a field be used instead of a property?
141 votes
6 answers
63k views

The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'

I have the following view model public class ProjectVM { .... [Display(Name = "Category")] [Required(ErrorMessage = "Please select a category")] public int CategoryID { get; set; } ...
user avatar
68 votes
4 answers
159k views

What are good ways to prevent SQL injection? [duplicate]

I have to program an application management system for my OJT company. The front end will be done in C# and the back end in SQL. Now I have never done a project of this scope before; in school we had ...
LeonidasFett's user avatar
  • 3,052
103 votes
7 answers
149k views

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

This question and community wiki answer has been added to assist in closing out numerous unanswered questions as discussed in this meta post. I have some code and when it executes, it throws an ...
user avatar
1176 votes
31 answers
1.1m views

Deserialize JSON into C# dynamic object? [duplicate]

Is there a way to deserialize JSON content into a C# dynamic type? It would be nice to skip creating a bunch of classes in order to use the DataContractJsonSerializer.
jswanson's user avatar
  • 16.3k
117 votes
7 answers
61k views

How to configure an app to run correctly on a machine with a high DPI setting (e.g. 150%)?

I've created a simple Winforms application in C#. When I run the application on a machine with high DPI settings (e.g. 150%), the application gets scaled up. So far so good! But instead of rendering ...
Boris's user avatar
  • 8,571
111 votes
4 answers
145k views

How to detect click/touch events on UI and GameObjects

How to detect UI object on Canvas on Touch in android? For example, I have a canvas that have 5 objects such as Image, RawImage, Buttons, InputField and so on. When I touch on Button UI object Then ...
Dennis Liu's user avatar
  • 2,268
959 votes
26 answers
656k views

Sending email in .NET through Gmail

Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible ...
Mike Wills's user avatar
980 votes
12 answers
604k views

How do I force my .NET application to run as administrator?

Once my program is installed on a client machine, how do I force my program to run as an administrator on Windows 7?
Gold's user avatar
  • 60.7k
2148 votes
47 answers
1.3m views

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?
745 votes
24 answers
326k views

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only ...
John Sheehan's user avatar
  • 77.5k
84 votes
4 answers
56k views

How to append whole set of model to formdata and obtain it in MVC

How do I pass a whole set model object through formdata and convert it to model type in the controller? Below is what I've tried! JavaScript part: model = { EventFromDate: fromDate, ...
Guruprasad J Rao's user avatar
970 votes
20 answers
700k views

Is there a way to check if a file is in use?

I'm writing a program in C# that needs to repeatedly access 1 image file. Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to ...
Dawsy's user avatar
  • 10.3k
291 votes
9 answers
212k views

Use of Application.DoEvents()

Can Application.DoEvents() be used in C#? Is this function a way to allow the GUI to catch up with the rest of the app, in much the same way that VB6's DoEvents does?
Craig Johnston's user avatar
146 votes
10 answers
59k views

How to handle both a single item and an array for the same property using JSON.net

I'm trying to fix my SendGridPlus library to deal with SendGrid events, but I'm having some trouble with the inconsistent treatment of categories in the API. In the following example payload taken ...
Robert McLaws's user avatar
172 votes
8 answers
267k views

Why does integer division in C# return an integer and not a float?

Does anyone know why integer division in C# returns an integer and not a float? What is the idea behind it? (Is it only a legacy of C/C++?) In C#: float x = 13 / 4; //== operator is overridden ...
BanditoBunny's user avatar
  • 3,668
66 votes
15 answers
530k views

What is the best way to parse html in C#? [closed]

I'm looking for a library/method to parse an html file with more html specific features than generic xml parsing libraries.
Luke's user avatar
  • 18.6k
1168 votes
24 answers
1.1m views

Get property value from string using reflection

I am trying implement the Data transformation using Reflection1 example in my code. The GetSourceValue function has a switch comparing various types, but I want to remove these types and properties ...
pedrofernandes's user avatar
3388 votes
31 answers
1.2m views

Case insensitive 'Contains(string)'

Is there a way to make the following return true? string title = "ASTRINGTOTEST"; title.Contains("string"); There doesn't seem to be an overload that allows me to set the case ...
Boris Callens's user avatar
49 votes
12 answers
87k views

Communicate between two windows forms in C#

I have two forms, one is the main form and the other is an options form. So say for example that the user clicks on my menu on the main form: Tools -> Options, this would cause my options form to ...
Bob Dylan's user avatar
  • 4,403
1387 votes
26 answers
1.2m views

How and when to use ‘async’ and ‘await’

From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perform long duration logic? I'...
Dan Dinu's user avatar
  • 32.5k
378 votes
9 answers
1.6m views

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

Consider: namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(...
huda's user avatar
  • 4,117
534 votes
16 answers
806k views

How to Deserialize XML document

How do I Deserialize this XML document: <?xml version="1.0" encoding="utf-8"?> <Cars> <Car> <StockNumber>1020</StockNumber> <Make>Nissan</Make> ...
Alex's user avatar
  • 39.3k
749 votes
29 answers
820k views

Encrypt and decrypt a string in C#? [closed]

How can I encrypt and decrypt a string in C#?
NotDan's user avatar
  • 31.7k
1460 votes
17 answers
2.4m views

Send HTTP POST request in .NET

How can I make an HTTP POST request and send data in the body?
Hooch's user avatar
  • 28.8k
1650 votes
15 answers
461k views

Why is it important to override GetHashCode when Equals method is overridden?

Given the following class public class Foo { public int FooId { get; set; } public string FooName { get; set; } public override bool Equals(object obj) { Foo fooItem = obj as ...
David Basarab's user avatar
1870 votes
20 answers
416k views

Proper use of the IDisposable interface

I know from reading Microsoft documentation that the "primary" use of the IDisposable interface is to clean up unmanaged resources. To me, "unmanaged" means things like database ...
cwick's user avatar
  • 26.1k
1721 votes
14 answers
627k views

What does the [Flags] Enum Attribute mean in C#?

From time to time I see an enum like the following: [Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 } I don't understand what ...
Brian Leahy's user avatar
  • 34.7k
145 votes
18 answers
69k views

Natural Sort Order in C#

Anyone have a good resource or provide a sample of a natural order sort in C# for an FileInfo array? I am implementing the IComparer interface in my sorts.
Michael Kniskern's user avatar
687 votes
10 answers
643k views

How do you do a deep copy of an object in .NET? [duplicate]

I want a true deep copy. In Java, this was easy, but how do you do it in C#?
user18931's user avatar
  • 10.7k
653 votes
24 answers
995k views

LEFT OUTER JOIN in LINQ

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Correct problem: For inner join is easy and I have a ...
Toy's user avatar
  • 6,583
48 votes
3 answers
7k views

How can I parse a JSON string that would cause illegal C# identifiers?

I have been using NewtonSoft JSON Convert library to parse and convert JSON string to C# objects. But now I have came across a really awkward JSON string and I am unable to convert it into C# object ...
TaLha Khan's user avatar
  • 2,423
1695 votes
28 answers
247k views

Why not inherit from List<T>?

When planning out my programs, I often start with a chain of thought like so: A football team is just a list of football players. Therefore, I should represent it with: var football_team = new ...
Superbest's user avatar
  • 25.3k
1327 votes
18 answers
1.2m views

How to call asynchronous method from synchronous method in C#?

I have a public async void Foo() method that I want to call from synchronous method. So far all I have seen from MSDN documentation is calling async methods via async methods, but my whole program is ...
Tower's user avatar
  • 99k
653 votes
7 answers
393k views

How to use HTML Agility pack

How do I use the HTML Agility Pack? My XHTML document is not completely valid. That's why I wanted to use it. How do I use it in my project? My project is in C#.
user avatar

1
2 3 4 5
3445