C# interview questions
22 questions with answers. 897 open jobs in India ask for C#.
What is the difference between String and string in C#?
stringis an alias in C# forSystem.String.
So technically, there is no difference. It's likeintvs.System.Int32.As far as guidelines, it's generally recommended to use
stringany time you're referring to an object.e.g.
string place = "world";Likewise, I think it's generally recommended to use
Stringif 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)
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
Outerbefore looking at thoseusingdirectives outside the namespace, so it findsOuter.Mathinstead ofSystem.Math. Unfortunately (or perhaps fortunately?),Outer.Mathhas noPImember, so File1 is now broken.This changes if you put the
usinginside 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
Systembefore searchingOuter, findsSystem.Math, and all is well.Some would argue that
Mathmight be a bad name for a user-defined class, since there's already one inSystem; 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
Foois in namespaceOuter, rather thanOuter.Inner. In that case, addingOuter.Mathin File2 breaks File1 regardless of where theusinggoes. This implies that the compiler searches the innermost enclosing namespace before it looks at anyusingdirective.From Stack Overflow: asked by benPearce, answered by Charlie (CC BY-SA 3.0)
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 higherDefaultValueAttributeis 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
DefaultValueAttributewill 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)
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
IOperationSingletonInstanceservice is using a specific instance with a known ID ofGuid.Empty, so it will be clear when this type is in use. We have also registered anOperationServicethat depends on each of the otherOperationtypes, 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
OperationsControllerthat requests each kind ofIOperationtype as well as anOperationService. TheIndexaction then displays all of the controller’s and service’sOperationIdvalues.Read the rest at the sourceFrom Stack Overflow: asked by Elvin Mammadov, answered by akardon (CC BY-SA 4.0)
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#toAnswer(if all Answers are null then theAnsweris 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)
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
forloop 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)
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(orNothingin VB.NET). This means you either set it tonull, or you never set it to anything at all.Like anything else,
nullgets passed around. If it isnullin method "A", it could be that method "B" passed anullto method "A".nullcan have different meanings:- Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a
NullReferenceException. - The developer is using
nullintentionally 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 assignnullto them to indicate there is no value stored in it, for exampleint? a = null;(which is a shortcut forNullable<int> a = null;) where the question mark indicates it is allowed to storenullin variablea. You can check that either withif (a.HasValue) {...}or withif (a==null) {...}. Nullable variables, likeain this example, allow to access the value viaa.Valueexplicitly, or just as normal viaa.
Note that accessing it viaa.Valuethrows anInvalidOperationExceptioninstead of aNullReferenceExceptionifaisnull- you should do the check beforehand, i.e. if you have another non-nullable variableint b;then you should do assignments likeif (a.HasValue) { b = a.Value; }or shorterif (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
runtimethrowing aNullReferenceExceptionalways 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 anullreference. The simplest case:string foo = null; foo.ToUpper();This will throw a
NullReferenceExceptionat the second line because you can't call the instance methodToUpper()on astringreference pointing tonull.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.memberIf 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.memberRead the rest at the sourceFrom Stack Overflow: asked by John Saunders, answered by John Saunders (CC BY-SA 4.0)
- Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a
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: 00001000Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR
|operator, AllowedColors looks like this:myProperties.AllowedColors: 00001110So 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
0in 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)
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
constVSreadonlyvalues can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen. const's are implicitlystatic. You use aClassName.ConstantNamenotation 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; } }AssemblyBreferencesAssemblyAand uses these values in code. When this is compiled:- in the case of the
constvalue, it is like a find-replace. The value 2 is 'baked into' theAssemblyB's IL. This means that if tomorrow I updateI_CONST_VALUEto 20,AssemblyBwould still have 2 till I recompile it. - in the case of the
readonlyvalue, it is like arefto a memory location. The value is not baked intoAssemblyB's IL. This means that if the memory location is updated,AssemblyBgets the new value without recompilation. So ifI_RO_VALUEis updated to 30, you only need to buildAssemblyAand 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)
- having to declare the value at the time of a definition for a
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 calledRosterthat is aList<Player>. And make itReadOnlyList<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)
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 customIEqualityComparer<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
Equalslogic; the rules are:- if two things are equal (
Equals(...) == true) then they must return the same value forGetHashCode() - if the
GetHashCode()is equal, it is not necessary for them to be the same; this is a collision, andEqualswill be called to see if it is a real equality or not.
In this case, it looks like "
return FooId;" is a suitableGetHashCode()implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so thatnew Foo(3,5)has a different hash-code tonew Foo(5,3)):In modern frameworks, the
HashCodetype 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 overridingEqualsandGetHashCode.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)
- if two things are equal (
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:
- It logically represents a single value, similar to primitive types (integer, double, and so on).
- It has an instance size smaller than 16 bytes.
- It is immutable.
- 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 }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:
- Each struct,
EntryandEnumerator, represent single values. - Speed
Entryis never passed as a parameter outside of the Dictionary class. Further investigation shows that in order to satisfy implementation of IEnumerable, Dictionary uses theEnumeratorstruct which it copies every time an enumerator is requested ...makes sense.- Internal to the Dictionary class.
Enumeratoris 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-typeIEnumeratoris 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:
- Nothing in the structs above is declared
readonly- not immutable - Size of these struct could be well over 16 bytes
Entryhas an undetermined lifetime (fromAdd(), toRemove(),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: 889msCapacity: 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)
'Static readonly' vs. 'const'
public static readonlyfields are a little unusual;public staticproperties (with only aget) would be more common (perhaps backed by aprivate static readonlyfield).constvalues 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 -
Zeroetc make reasonable consts ;p Other than that,staticproperties are more common.From Stack Overflow: asked by Svish, answered by Marc Gravell (CC BY-SA 4.0)
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)
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 theHashtableclass?", then it's an easy answer:Dictionary<TKey, TValue>is a generic type,Hashtableis not. That means you get type safety withDictionary<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 theHashtable, as you can tell from this comment in its source code:The generic Dictionary was copied from Hashtable's source
From Stack Overflow: asked by Nakul Chaudhary, answered by Michael Madsen (CC BY-SA 3.0)
How can I calculate the difference between two dates (number of days)?
Assuming
StartDateandEndDateare of typeDateTime:(EndDate - StartDate).TotalDaysFrom Stack Overflow: asked by leora, answered by Greg Beech (CC BY-SA 3.0)
How and when to use ‘async’ and ‘await’
When using
asyncandawaitthe 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:
Task<int> longRunningTask = LongRunningOperationAsync();starts executingLongRunningOperationIndependent work is done on let's assume the Main Thread (Thread ID = 1) then
await longRunningTaskis reached.Now, if the
longRunningTaskhasn't finished and it is still running,MyMethodAsync()will return to its calling method, thus the main thread doesn't get blocked. When thelongRunningTaskis done then a thread from the ThreadPool (can be any thread) will return toMyMethodAsync()in its previous context and continue execution (in this case printing the result to the console).
A second case would be that the
longRunningTaskhas already finished its execution and the result is available. When reaching theawait longRunningTaskwe 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 aTask.Delay(1000)involved.From Stack Overflow: asked by Dan Dinu, answered by Dan Dinu (CC BY-SA 4.0)
Difference Between Select and SelectMany
SelectManyflattens queries that return lists of lists. For examplepublic 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 });From Stack Overflow: asked by Tarik, answered by Mike Two (CC BY-SA 3.0)
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)
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)
How to make '.Contains(string)' case insensitive?
You could use the
String.IndexOfMethod and passStringComparison.OrdinalIgnoreCaseas 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 useif (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)
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.
- Stack Overflowby its contributors, named on each answerCC BY-SA22 questions