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 Microsoft's .NET ecosystem, 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
7532 votes
68 answers
1.3m views

What is the difference between String and string in C#?

What are the differences between these two, and which one should I use? string s = "Hello world!"; String s = "Hello world!";
4380 votes
36 answers
1.0m views

How to enumerate an enum?

How can you enumerate an enum in C#? E.g. the following code does not compile: public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { ...
Ian Boyd's user avatar
  • 252k
3900 votes
32 answers
2.0m views

How do I cast int to enum in C#?

How do I cast an int to an enum in C#?
lomaxx's user avatar
  • 115k
3435 votes
32 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
3305 votes
20 answers
2.4m views

How to iterate over a dictionary?

I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
Jake Stewart's user avatar
  • 33.3k
2897 votes
13 answers
427k views

What are the correct version numbers for C#?

What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5? This question is primarily to aid those who are searching for an answer using an incorrect ...
2638 votes
59 answers
1.0m 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
2568 votes
29 answers
846k views

Catch multiple exceptions at once?

It is discouraged to catch System.Exception errors. Instead, only the "known" exceptions should be caught. This sometimes leads to unnecessary repetitive code, for example: try { WebId = ...
Michael Stum's user avatar
2421 votes
32 answers
3.1m views

How do I generate a random integer in C#?

How do I generate a random integer in C#?
Rella's user avatar
  • 66k
2406 votes
15 answers
281k views

Should 'using' directives be inside or outside the namespace in C#?

I have been running StyleCop over some C# code, and it keeps reporting that my using directives should be inside the namespace. Is there a technical reason for putting the using directives inside ...
benPearce's user avatar
  • 38.1k
2365 votes
41 answers
1.2m views

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding? I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know ...
Agnel Kurian's user avatar
  • 58.7k
2352 votes
31 answers
2.3m views

Get int value from enum in C#

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this. public enum Question { Role = 2, ProjectFunding = 3, ...
jim's user avatar
  • 27k
2323 votes
23 answers
1.3m views

What is the best way to give a C# auto-property an initial value?

How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. Using the Constructor: class Person { public Person() { Name = "...
bentford's user avatar
  • 33.2k
2249 votes
75 answers
829k views

How do I calculate someone's age based on a DateTime type birthday?

Given a DateTime representing a person's birthday, how do I calculate their age in years?
2167 votes
48 answers
1.4m 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?
2098 votes
14 answers
1.5m views

AddTransient, AddScoped and AddSingleton Services Differences

I want to implement dependency injection (DI) in ASP.NET Core. So after adding this code to ConfigureServices method, both ways work. What is the difference between the services.AddTransient and ...
Elvin Mammadov's user avatar
2098 votes
113 answers
1.8m views

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

A C# desktop application (on the Visual Studio Express edition) worked, but then it didn't work 5 seconds later. I tried the following: Ensure debug configuration, debug flag, and full debug ...
2011 votes
18 answers
695k views

What do two question marks together mean in C#?

Ran across this line of code: FormsAuth = formsAuth ?? new FormsAuthenticationWrapper(); What do the two question marks mean, is it some kind of ternary operator? It's hard to look up in Google.
Edward Tanguay's user avatar
1898 votes
16 answers
1.5m views

Type Checking: typeof, GetType, or is?

I've seen many people use the following code: Type t = typeof(SomeType); if (t == typeof(int)) // Some code here But I know you could also do this: if (obj1.GetType() == typeof(int)) // Some ...
jasonh's user avatar
  • 29.9k
1891 votes
20 answers
429k 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.4k
1869 votes
26 answers
2.3m 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?
1865 votes
4 answers
121k views

Is there a reason for C#'s reuse of the variable in a foreach?

When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example: foreach (var s in strings) { query = query.Where(i => i.Prop ...
StriplingWarrior's user avatar
1856 votes
10 answers
1.4m views

Calling the base constructor in C#

If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that? For example, if I inherit from the ...
lomaxx's user avatar
  • 115k
1753 votes
14 answers
658k 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
  • 35.1k
1752 votes
8 answers
978k views

How to loop through all enum values in C#? [duplicate]

This question already has an answer here: How do I enumerate an enum in C#? 26 answers public enum Foos { A, B, C } Is there a way to loop through the possible values of Foos? ...
divinci's user avatar
  • 22.7k
1718 votes
29 answers
252k 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
  • 26k
1700 votes
30 answers
515k views

What is the difference between const and readonly in C#?

What is the difference between const and readonly in C#? When would you use one over the other?
readonly's user avatar
  • 349k
1660 votes
16 answers
471k 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
1654 votes
42 answers
203k views

Calculate relative time in C#

Given a specific DateTime value, how do I display relative time, like: 2 hours ago 3 days ago a month ago
1649 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?
1638 votes
24 answers
1.8m views

How to Sort a List<T> by a property in the object

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class: List<Order> objListOrder = new List<Order>(); ...
Shyju's user avatar
  • 217k
1637 votes
31 answers
363k views

When should I use a struct rather than a class in C#?

When should you use struct and not class in C#? My conceptual model is that structs are used in times when the item is merely a collection of value types. A way to logically hold them all together ...
Alex Baranosky's user avatar
1635 votes
6 answers
121k views

Try-catch speeding up my code?

I wrote some code for testing the impact of try-catch, but seeing some surprising results. static void Main(string[] args) { Thread.CurrentThread.Priority = ThreadPriority.Highest; Process....
Eren Ersönmez's user avatar
1596 votes
22 answers
483k views

'Static readonly' vs. 'const'

I've read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my ...
Svish's user avatar
  • 155k
1592 votes
47 answers
837k 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.4k
1568 votes
19 answers
607k views

Why is Dictionary preferred over Hashtable in C#?

In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
Nakul Chaudhary's user avatar
1552 votes
33 answers
711k 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?
1512 votes
41 answers
490k views

Path.Combine for URLs?

Path.Combine is handy, but is there a similar function in the .NET framework for URLs? I'm looking for syntax like this: Url.Combine("http://MyUrl.com/", "/Images/Image.jpg") which would return: "...
Brian MacKay's user avatar
  • 31.6k
1491 votes
18 answers
224k views

Virtual member call in a constructor

I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor. Why would this be something not to do?
JasonS's user avatar
  • 23.7k
1483 votes
17 answers
2.5m 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
  • 29.3k
1478 votes
23 answers
1.3m views

LINQ's Distinct() on a particular property

I am playing with LINQ to learn about it, but I can't figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I ...
Patrick Desjardins's user avatar
1473 votes
296 answers
754k views

Hidden Features of C#? [closed]

This came to my mind after I learned the following from this question: where T : struct We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc. Some ...
1463 votes
17 answers
1.7m views

How to calculate difference between two dates (number of days)?

How can one calculate the number of days between two dates in C#?
leora's user avatar
  • 193k
1438 votes
22 answers
503k views

Create Generic method constraining T to an Enum

I'm building a function to extend the Enum.Parse concept that Allows a default value to be parsed in case that an Enum value is not found Is case insensitive So I wrote the following: public static ...
johnc's user avatar
  • 39.9k
1433 votes
31 answers
748k views

JavaScriptSerializer - JSON serialization of enum as string

I have a class that contains an enum property, and upon serializing the object using JavaScriptSerializer, my json result contains the integer value of the enumeration rather than its string "...
Omer Bokhari's user avatar
  • 58.5k
1429 votes
13 answers
1.0m views

Multiline string literal in C#

Is there an easy way to create a multiline string literal in C#? Here's what I have now: string query = "SELECT foo, bar" + " FROM table" + " WHERE id = 42"; I know PHP has <<<BLOCK ...
Chet's user avatar
  • 21.7k
1409 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
  • 33k
1378 votes
16 answers
1.3m views

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

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

Difference Between Select and SelectMany

I've been searching the difference between Select and SelectMany but I haven't been able to find a suitable answer. I need to learn the difference when using LINQ To SQL but all I've found are ...
Tarik's user avatar
  • 80.8k
1345 votes
4 answers
107k views

\d less efficient than [0-9]

I made a comment yesterday on an answer where someone had used [0123456789] in a regex rather than [0-9] or \d. I said it was probably more efficient to use a range or digit specifier than a character ...
weston's user avatar
  • 54.5k

1
2 3 4 5
32329