All topics

C# interview questions

22 questions with answers. 897 open jobs in India ask for C#.

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

    string is an alias in C# for System.String.
    So technically, there is no difference. It's like int vs. System.Int32.

    As far as guidelines, it's generally recommended to use string any time you're referring to an object.

    e.g.

    string place = "world";
    

    Likewise, I think it's generally recommended to use String if you need to refer specifically to the class.

    e.g.

    string greet = String.Format("Hello {0}!", place);
    

    This is the style that Microsoft tends to use in their examples.

    It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases.

    From Stack Overflow: asked by Lance Fisher, answered by Derek Park (CC BY-SA 4.0)

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

    There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:

    // File1.cs
    using System;
    namespace Outer.Inner
    {
        class Foo
        {
            static void Bar()
            {
                double d = Math.PI;
            }
        }
    }
    

    Now imagine that someone adds another file (File2.cs) to the project that looks like this:

    // File2.cs
    namespace Outer
    {
        class Math
        {
        }
    }
    

    The compiler searches Outer before looking at those using directives outside the namespace, so it finds Outer.Math instead of System.Math. Unfortunately (or perhaps fortunately?), Outer.Math has no PI member, so File1 is now broken.

    This changes if you put the using inside your namespace declaration, as follows:

    // File1b.cs
    namespace Outer.Inner
    {
        using System;
        class Foo
        {
            static void Bar()
            {
                double d = Math.PI;
            }
        }
    }
    

    Now the compiler searches System before searching Outer, finds System.Math, and all is well.

    Some would argue that Math might be a bad name for a user-defined class, since there's already one in System; the point here is just that there is a difference, and it affects the maintainability of your code.

    It's also interesting to note what happens if Foo is in namespace Outer, rather than Outer.Inner. In that case, adding Outer.Math in File2 breaks File1 regardless of where the using goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any using directive.

    From Stack Overflow: asked by benPearce, answered by Charlie (CC BY-SA 3.0)

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

    In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

    Since C# 6.0, you can specify initial value in-line. The syntax is:

    public int X { get; set; } = x; // C# 6 or higher
    

    DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

    At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

    Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

    From Stack Overflow: asked by bentford, answered by Darren Kopp (CC BY-SA 4.0)

  4. AddTransient, AddScoped and AddSingleton Services Differences

    TL;DR

    Transient objects are always different; a new instance is provided to every controller and every service.

    Scoped objects are the same within a request, but different across different requests.

    Singleton objects are the same for every object and every request.

    For more clarification, this example from .NET documentation shows the difference:

    To demonstrate the difference between these lifetime and registration options, consider a simple interface that represents one or more tasks as an operation with a unique identifier, OperationId. Depending on how we configure the lifetime for this service, the container will provide either the same or different instances of the service to the requesting class. To make it clear which lifetime is being requested, we will create one type per lifetime option:

    using System;
    namespace DependencyInjectionSample.Interfaces
    {
        public interface IOperation
        {
            Guid OperationId { get; }
        }
        public interface IOperationTransient : IOperation
        {
        }
        public interface IOperationScoped : IOperation
        {
        }
        public interface IOperationSingleton : IOperation
        {
        }
        public interface IOperationSingletonInstance : IOperation
        {
        }
    }
    

    We implement these interfaces using a single class, Operation, that accepts a GUID in its constructor, or uses a new GUID if none is provided:

    using System;
    using DependencyInjectionSample.Interfaces;
    namespace DependencyInjectionSample.Classes
    {
        public class Operation : IOperationTransient, IOperationScoped, IOperationSingleton, IOperationSingletonInstance
        {
            Guid _guid;
            public Operation() : this(Guid.NewGuid())
            {
            }
            public Operation(Guid guid)
            {
                _guid = guid;
            }
            public Guid OperationId => _guid;
        }
    }
    

    Next, in ConfigureServices, each type is added to the container according to its named lifetime:

    services.AddTransient<IOperationTransient, Operation>();
    services.AddScoped<IOperationScoped, Operation>();
    services.AddSingleton<IOperationSingleton, Operation>();
    services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
    services.AddTransient<OperationService, OperationService>();
    

    Note that the IOperationSingletonInstance service is using a specific instance with a known ID of Guid.Empty, so it will be clear when this type is in use. We have also registered an OperationService that depends on each of the other Operation types, so that it will be clear within a request whether this service is getting the same instance as the controller, or a new one, for each operation type. All this service does is expose its dependencies as properties, so they can be displayed in the view.

    using DependencyInjectionSample.Interfaces;
    namespace DependencyInjectionSample.Services
    {
        public class OperationService
        {
            public IOperationTransient TransientOperation { get; }
            public IOperationScoped ScopedOperation { get; }
            public IOperationSingleton SingletonOperation { get; }
            public IOperationSingletonInstance SingletonInstanceOperation { get; }
            public OperationService(IOperationTransient transientOperation,
                IOperationScoped scopedOperation,
                IOperationSingleton singletonOperation,
                IOperationSingletonInstance instanceOperation)
            {
                TransientOperation = transientOperation;
                ScopedOperation = scopedOperation;
                SingletonOperation = singletonOperation;
                SingletonInstanceOperation = instanceOperation;
            }
        }
    }
    

    To demonstrate the object lifetimes within and between separate individual requests to the application, the sample includes an OperationsController that requests each kind of IOperation type as well as an OperationService. The Index action then displays all of the controller’s and service’s OperationId values.

    Read the rest at the sourceFrom Stack Overflow: asked by Elvin Mammadov, answered by akardon (CC BY-SA 4.0)

  5. What do two question marks together mean in C#?

    It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also ?? Operator - MSDN.

    FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
    

    expands to:

    FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
    

    which further expands to:

    if(formsAuth != null)
        FormsAuth = formsAuth;
    else
        FormsAuth = new FormsAuthenticationWrapper();
    

    In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."

    Note that you can use any number of these in sequence. The following statement will assign the first non-null Answer# to Answer (if all Answers are null then the Answer is null):

    string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;
    

    Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once. This is important if for example an expression is a method call with side effects. (Credit to @Joey for pointing this out.)

    From Stack Overflow: asked by Edward Tanguay, answered by lc. (CC BY-SA 4.0)

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

    The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.

    Your criticism is entirely justified.

    I discuss this problem in detail here:

    Closing over the loop variable considered harmful

    Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?

    The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

    I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

    The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

    From Stack Overflow: asked by StriplingWarrior, answered by Eric Lippert (CC BY-SA 3.0)

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

    What is the cause?

    Bottom Line

    You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all.

    Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".

    null can have different meanings:

    1. Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a NullReferenceException.
    2. The developer is using null intentionally to indicate there is no meaningful value available. Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) - you can assign null to them to indicate there is no value stored in it, for example int? a = null; (which is a shortcut for Nullable<int> a = null;) where the question mark indicates it is allowed to store null in variable a. You can check that either with if (a.HasValue) {...} or with if (a==null) {...}. Nullable variables, like a in this example, allow to access the value via a.Value explicitly, or just as normal via a.
      Note that accessing it via a.Value throws an InvalidOperationException instead of a NullReferenceException if a is null - you should do the check beforehand, i.e. if you have another non-nullable variable int b; then you should do assignments like if (a.HasValue) { b = a.Value; } or shorter if (a != null) { b = a; }.

    The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.

    More Specifically

    The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference, and the reference is not initialized (or it was once initialized, but is no longer initialized).

    This means the reference is null, and you cannot access members (such as methods) through a null reference. The simplest case:

    string foo = null;
    foo.ToUpper();
    

    This will throw a NullReferenceException at the second line because you can't call the instance method ToUpper() on a string reference pointing to null.

    Debugging

    How do you find the source of a NullReferenceException? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.

    If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable, and verify that it points to an instance when you expect it to.

    By following the program flow this way, you can find the location where the instance should not be null, and why it isn't properly set.

    Examples

    Some common scenarios where the exception can be thrown:

    Generic

    ref1.ref2.ref3.member
    

    If ref1 or ref2 or ref3 is null, then you'll get a NullReferenceException. If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:

    var r1 = ref1;
    var r2 = r1.ref2;
    var r3 = r2.ref3;
    r3.member
    

    Read the rest at the sourceFrom Stack Overflow: asked by John Saunders, answered by John Saunders (CC BY-SA 4.0)

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

    The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:

    var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
    

    Note that the [Flags] attribute doesn't enable this by itself - all it does is allow a nice representation by the .ToString() method:

    enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
    [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
    ...
    var str1 = (Suits.Spades | Suits.Diamonds).ToString();
               // "5"
    var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
               // "Spades, Diamonds"
    

    It is also important to note that [Flags] does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment.

    Incorrect declaration:

    [Flags]
    public enum MyColors
    {
        Yellow,  // 0
        Green,   // 1
        Red,     // 2
        Blue     // 3
    }
    

    The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.

    Here's an example of a correct declaration:

    [Flags]
    public enum MyColors
    {
        Yellow = 1,
        Green = 2,
        Red = 4,
        Blue = 8
    }
    

    To retrieve the distinct values in your property, one can do this:

    if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
    {
        // Yellow is allowed...
    }
    

    or prior to .NET 4:

    if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
    {
        // Yellow is allowed...
    }
    if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
    {
        // Green is allowed...
    }    
    

    Under the covers

    This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:

     Yellow: 00000001
     Green:  00000010
     Red:    00000100
     Blue:   00001000
    

    Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR | operator, AllowedColors looks like this:

    myProperties.AllowedColors: 00001110
    

    So when you retrieve the value you are actually performing bitwise AND & on the values:

    myProperties.AllowedColors: 00001110
                 MyColor.Green: 00000010
                 -----------------------
                                00000010 // Hey, this is the same as MyColor.Green!
    

    The None = 0 value

    And regarding the use of 0 in your enumeration, quoting from MSDN:

    [Flags]
    public enum MyColors
    {
        None = 0,
        ....
    }
    

    Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.

    You can find more info about the flags attribute and its usage at msdn and designing flags at msdn

    From Stack Overflow: asked by Brian Leahy, answered by andynil (CC BY-SA 4.0)

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

    Apart from the apparent difference of

    • having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen.
    • const's are implicitly static. You use a ClassName.ConstantName notation to access them.

    There is a subtle difference. Consider a class defined in AssemblyA.

    public class Const_V_Readonly
    {
      public const int I_CONST_VALUE = 2;
      public readonly int I_RO_VALUE;
      public Const_V_Readonly()
      {
         I_RO_VALUE = 3;
      }
    }
    

    AssemblyB references AssemblyA and uses these values in code. When this is compiled:

    • in the case of the const value, it is like a find-replace. The value 2 is 'baked into' the AssemblyB's IL. This means that if tomorrow I update I_CONST_VALUE to 20, AssemblyB would still have 2 till I recompile it.
    • in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA and all clients do not need to be recompiled.

    So if you are confident that the value of the constant won't change, use a const.

    public const int CM_IN_A_METER = 100;
    

    But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a readonly.

    public readonly float PI = 3.14;
    

    Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: Effective C# - Bill Wagner

    From Stack Overflow: asked by readonly, answered by Gishu (CC BY-SA 4.0)

  10. Why not inherit from List<T>?

    There are some good answers here. I would add to them the following points.

    What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?

    Ask any ten non-computer-programmer people who are familiar with the existence of football to fill in the blank:

    A football team is a particular kind of _____

    Did anyone say "list of football players with a few bells and whistles", or did they all say "sports team" or "club" or "organization"? Your notion that a football team is a particular kind of list of players is in your human mind and your human mind alone.

    List<T> is a mechanism. Football team is a business object -- that is, an object that represents some concept that is in the business domain of the program. Don't mix those! A football team is a kind of team; it has a roster, a roster is a list of players. A roster is not a particular kind of list of players. A roster is a list of players. So make a property called Roster that is a List<Player>. And make it ReadOnlyList<Player> while you're at it, unless you believe that everyone who knows about a football team gets to delete players from the roster.

    Is inheriting from List<T> always unacceptable?

    Unacceptable to whom? Me? No.

    When is it acceptable?

    When you're building a mechanism that extends the List<T> mechanism.

    What must a programmer consider, when deciding whether to inherit from List<T> or not?

    Am I building a mechanism or a business object?

    But that's a lot of code! What do I get for all that work?

    You spent more time typing up your question that it would have taken you to write forwarding methods for the relevant members of List<T> fifty times over. You're clearly not afraid of verbosity, and we are talking about a very small amount of code here; this is a few minutes work.

    UPDATE

    I gave it some more thought and there is another reason to not model a football team as a list of players. In fact it might be a bad idea to model a football team as having a list of players too. The problem with a team as/having a list of players is that what you've got is a snapshot of the team at a moment in time. I don't know what your business case is for this class, but if I had a class that represented a football team I would want to ask it questions like "how many Seahawks players missed games due to injury between 2003 and 2013?" or "What Denver player who previously played for another team had the largest year-over-year increase in yards ran?" or "Did the Piggers go all the way this year?"

    That is, a football team seems to me to be well modeled as a collection of historical facts such as when a player was recruited, injured, retired, etc. Obviously the current player roster is an important fact that should probably be front-and-center, but there may be other interesting things you want to do with this object that require a more historical perspective.

    From Stack Overflow: asked by Superbest, answered by Eric Lippert (CC BY-SA 4.0)

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

    Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>, etc - since this is used (in the absence of a custom IEqualityComparer<T>) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called).

    The GetHashCode() method should reflect the Equals logic; the rules are:

    • if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode()
    • if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not.

    In this case, it looks like "return FooId;" is a suitable GetHashCode() implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that new Foo(3,5) has a different hash-code to new Foo(5,3)):

    In modern frameworks, the HashCode type has methods to help you create a hashcode from multiple values; on older frameworks, you'd need to go without, so something like:

    unchecked // only needed if you're compiling with arithmetic checks enabled
    { // (the default compiler behaviour is *disabled*, so most folks won't need this)
        int hash = 13;
        hash = (hash * 7) + field1.GetHashCode();
        hash = (hash * 7) + field2.GetHashCode();
        ...
        return hash;
    }
    

    Oh - for convenience, you might also consider providing == and != operators when overriding Equals and GetHashCode.

    A demonstration of what happens when you get this wrong is here.

    From Stack Overflow: asked by David Basarab, answered by Marc Gravell (CC BY-SA 4.0)

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

    The source referenced by the OP has some credibility ...but what about Microsoft - what is the stance on struct usage? I sought some extra learning from Microsoft, and here is what I found:

    Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

    Do not define a structure unless the type has all of the following characteristics:

    1. It logically represents a single value, similar to primitive types (integer, double, and so on).
    2. It has an instance size smaller than 16 bytes.
    3. It is immutable.
    4. It will not have to be boxed frequently.

    Microsoft consistently violates those rules

    Okay, #2 and #3 anyway. Our beloved dictionary has 2 internal structs:

    [StructLayout(LayoutKind.Sequential)]  // default for structs
    private struct Entry  //<Tkey, TValue>
    {
        //  View code at *Reference Source
    }
    [Serializable, StructLayout(LayoutKind.Sequential)]
    public struct Enumerator : 
        IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, 
        IDictionaryEnumerator, IEnumerator
    {
        //  View code at *Reference Source
    }
    

    *Reference Source

    The 'JonnyCantCode.com' source got 3 out of 4 - quite forgivable since #4 probably wouldn't be an issue. If you find yourself boxing a struct, rethink your architecture.

    Let's look at why Microsoft would use these structs:

    1. Each struct, Entry and Enumerator, represent single values.
    2. Speed
    3. Entry is never passed as a parameter outside of the Dictionary class. Further investigation shows that in order to satisfy implementation of IEnumerable, Dictionary uses the Enumerator struct which it copies every time an enumerator is requested ...makes sense.
    4. Internal to the Dictionary class. Enumerator is public because Dictionary is enumerable and must have equal accessibility to the IEnumerator interface implementation - e.g. IEnumerator getter.

    Update - In addition, realize that when a struct implements an interface - as Enumerator does - and is cast to that implemented type, the struct becomes a reference type and is moved to the heap. Internal to the Dictionary class, Enumerator is still a value type. However, as soon as a method calls GetEnumerator(), a reference-type IEnumerator is returned.

    What we don't see here is any attempt or proof of requirement to keep structs immutable or maintaining an instance size of only 16 bytes or less:

    1. Nothing in the structs above is declared readonly - not immutable
    2. Size of these struct could be well over 16 bytes
    3. Entry has an undetermined lifetime (from Add(), to Remove(), Clear(), or garbage collection);

    And ... 4. Both structs store TKey and TValue, which we all know are quite capable of being reference types (added bonus info)

    Hashed keys notwithstanding, dictionaries are fast in part because instancing a struct is quicker than a reference type. Here, I have a Dictionary<int, int> that stores 300,000 random integers with sequentially incremented keys.

    Capacity: 312874
    MemSize: 2660827 bytes
    Completed Resize: 5ms
    Total time to fill: 889ms

    Capacity: number of elements available before the internal array must be resized.

    MemSize: determined by serializing the dictionary into a MemoryStream and getting a byte length (accurate enough for our purposes).

    Completed Resize: the time it takes to resize the internal array from 150862 elements to 312874 elements. When you figure that each element is sequentially copied via Array.CopyTo(), that ain't too shabby.

    Read the rest at the sourceFrom Stack Overflow: asked by Alex Baranosky, answered by IAbstract (CC BY-SA 3.0)

  13. 'Static readonly' vs. 'const'

    public static readonly fields are a little unusual; public static properties (with only a get) would be more common (perhaps backed by a private static readonly field).

    const values are burned directly into the call-site; this is double edged:

    • it is useless if the value is fetched at runtime, perhaps from config
    • if you change the value of a const, you need to rebuild all the clients
    • but it can be faster, as it avoids a method call...
    • ...which might sometimes have been inlined by the JIT anyway

    If the value will never change, then const is fine - Zero etc make reasonable consts ;p Other than that, static properties are more common.

    From Stack Overflow: asked by Svish, answered by Marc Gravell (CC BY-SA 4.0)

  14. What is the difference between a field and a property?

    Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

    public class MyClass
    {
        // this is a field.  It is private to your class and stores the actual data.
        private string _myField;
        // this is a property. When accessed it uses the underlying field,
        // but only exposes the contract, which will not be affected by the underlying field
        public string MyProperty
        {
            get
            {
                return _myField;
            }
            set
            {
                _myField = value;
            }
        }
        // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
        // used to generate a private field for you
        public int AnotherProperty { get; set; } 
    }
    

    @Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.

    @GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.

    From Stack Overflow: asked by Anonymous, answered by Cory (CC BY-SA 4.0)

  15. Why is Dictionary preferred over Hashtable in C#?

    For what it's worth, a Dictionary is (conceptually) a hash table.

    If you meant "why do we use the Dictionary<TKey, TValue> class instead of the Hashtable class?", then it's an easy answer: Dictionary<TKey, TValue> is a generic type, Hashtable is not. That means you get type safety with Dictionary<TKey, TValue>, because you can't insert any random object into it, and you don't have to cast the values you take out.

    Interestingly, the Dictionary<TKey, TValue> implementation in the .NET Framework is based on the Hashtable, as you can tell from this comment in its source code:

    The generic Dictionary was copied from Hashtable's source

    Source

    From Stack Overflow: asked by Nakul Chaudhary, answered by Michael Madsen (CC BY-SA 3.0)

  16. How can I calculate the difference between two dates (number of days)?

    Assuming StartDate and EndDate are of type DateTime:

    (EndDate - StartDate).TotalDays
    

    From Stack Overflow: asked by leora, answered by Greg Beech (CC BY-SA 3.0)

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

    When using async and await the compiler generates a state machine in the background.

    Here's an example on which I hope I can explain some of the high-level details that are going on:

    public async Task MyMethodAsync()
    {
        Task<int> longRunningTask = LongRunningOperationAsync();
        // independent work which doesn't need the result of LongRunningOperationAsync can be done here
        //and now we call await on the task 
        int result = await longRunningTask;
        //use the result 
        Console.WriteLine(result);
    }
    public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation 
    {
        await Task.Delay(1000); // 1 second delay
        return 1;
    }
    

    OK, so what happens here:

    1. Task<int> longRunningTask = LongRunningOperationAsync(); starts executing LongRunningOperation

    2. Independent work is done on let's assume the Main Thread (Thread ID = 1) then await longRunningTask is reached.

      Now, if the longRunningTask hasn't finished and it is still running, MyMethodAsync() will return to its calling method, thus the main thread doesn't get blocked. When the longRunningTask is done then a thread from the ThreadPool (can be any thread) will return to MyMethodAsync() in its previous context and continue execution (in this case printing the result to the console).

    A second case would be that the longRunningTask has already finished its execution and the result is available. When reaching the await longRunningTask we already have the result so the code will continue executing on the very same thread. (in this case printing result to console). Of course this is not the case for the above example, where there's a Task.Delay(1000) involved.

    From Stack Overflow: asked by Dan Dinu, answered by Dan Dinu (CC BY-SA 4.0)

  18. Difference Between Select and SelectMany

    SelectMany flattens queries that return lists of lists. For example

    public class PhoneNumber
    {
        public string Number { get; set; }
    }
    public class Person
    {
        public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
        public string Name { get; set; }
    }
    IEnumerable<Person> people = new List<Person>();
    // Select gets a list of lists of phone numbers
    IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);
    // SelectMany flattens it to just a list of phone numbers.
    IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
    // And to include data from the parent in the result: 
    // pass an expression to the second parameter (resultSelector) in the overload:
    var directory = people
       .SelectMany(p => p.PhoneNumbers,
                   (parent, child) => new { parent.Name, child.Number });
    

    Live Demo on .NET Fiddle

    From Stack Overflow: asked by Tarik, answered by Mike Two (CC BY-SA 3.0)

  19. How can I enumerate an enum?

    If you're using .NET 5 or newer, use this solution.

    foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
    {
    }
    

    Note: The cast to (Suit[]) is not strictly necessary, but it does make the code 0.5 ns faster.

    From Stack Overflow: asked by Ian Boyd, answered by jop (CC BY-SA 4.0)

  20. How do I cast int to enum in C#?

    From an int:

    YourEnum foo = (YourEnum)yourInt;
    

    From a string:

    YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
    // The foo.ToString().Contains(",") check is necessary for 
    // enumerations marked with a [Flags] attribute.
    if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
    {
        throw new InvalidOperationException(
            $"{yourString} is not an underlying value of the YourEnum enumeration."
        );
    }
    

    Dynamically (type not known at compile-time):

    Type enumType = ...;
    // NB: Enums can specify a base type other than 'int'
    int numericValue = ...;
    object boxedEnumValue = Enum.ToObject(enumType, numericValue);
    

    From Stack Overflow: asked by lomaxx, answered by FlySwat (CC BY-SA 4.0)

  21. How to make '.Contains(string)' case insensitive?

    You could use the String.IndexOf Method and pass StringComparison.OrdinalIgnoreCase as the type of search to use:

    string title = "STRING";
    bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;
    

    Even better is defining a new extension method for string:

    public static class StringExtensions
    {
        public static bool Contains(this string source, string toCheck, StringComparison comp)
        {
            return source?.IndexOf(toCheck, comp) >= 0;
        }
    }
    

    Note, that null propagation ?. is available since C# 6.0 (VS 2015), for older versions use

    if (source == null) return false;
    return source.IndexOf(toCheck, comp) >= 0;
    

    USAGE:

    string title = "STRING";
    bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);
    

    From Stack Overflow: asked by Boris Callens, answered by JaredPar (CC BY-SA 4.0)

  22. How to iterate over a dictionary?
    foreach(KeyValuePair<string, string> entry in myDictionary)
    {
        // do something with entry.Value or entry.Key
    }
    

    From Stack Overflow: asked by Jake Stewart, answered by Pablo Fernandez (CC BY-SA 3.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.