.NET interview questions
12 questions with answers. 728 open jobs in India ask for .NET.
Difference between decimal, float and double in .NET?
float(the C# alias forSystem.Single) anddouble(the C# alias forSystem.Double) are floating binary point types.floatis 32-bit;doubleis 64-bit. In other words, they represent a number like this:10001.10010110011The binary number and the location of the binary point are both encoded within the value.
decimal(the C# alias forSystem.Decimal) is a floating decimal point type. In other words, they represent a number like this:12345.65789Again, the number and the location of the decimal point are both encoded within the value – that's what makes
decimalstill a floating point type instead of a fixed point type.The important thing to note is that humans are used to representing non-integers in a decimal form, and expect exact results in decimal representations; not all decimal numbers are exactly representable in binary floating point – 0.1, for example – so if you use a binary floating point value you'll actually get an approximation to 0.1. You'll still get approximations when using a floating decimal point as well – the result of dividing 1 by 3 can't be exactly represented, for example.
As for what to use when:
For values which are "naturally exact decimals" it's good to use
decimal. This is usually suitable for any concepts invented by humans: financial values are the most obvious example, but there are others too. Consider the score given to divers or ice skaters, for example.For values which are more artefacts of nature which can't really be measured exactly anyway,
float/doubleare more appropriate. For example, scientific data would usually be represented in this form. Here, the original values won't be "decimally accurate" to start with, so it's not important for the expected results to maintain the "decimal accuracy". Floating binary point types are much faster to work with than decimals.
From Stack Overflow: asked by Tom, answered by Jon Skeet (CC BY-SA 4.0)
What is the best algorithm for overriding GetHashCode?
I usually go with something like the implementation given in Josh Bloch's fabulous Effective Java. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:
public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = 17; // Suitable nullity checks etc, of course :) hash = hash * 23 + field1.GetHashCode(); hash = hash * 23 + field2.GetHashCode(); hash = hash * 23 + field3.GetHashCode(); return hash; } }As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-FNV example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant is prime though. I don't know quite how important that is.)
This is better than the common practice of
XORing hashcodes for two main reasons. Suppose we have a type with twointfields:XorHash(x, x) == XorHash(y, y) == 0 for all x, y XorHash(x, y) == XorHash(y, x) for all x, yBy the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.
This page gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The FNV alternative is similarly simple, but uses different constants and
XORinstead ofADDas a combining operation. It looks something like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.// Note: Not quite FNV! public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = (int) 2166136261; // Suitable nullity checks etc, of course :) hash = (hash * 16777619) ^ field1.GetHashCode(); hash = (hash * 16777619) ^ field2.GetHashCode(); hash = (hash * 16777619) ^ field3.GetHashCode(); return hash; } }Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.
As per the documentation:
You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:
- You can compute the hash code from fields that are not mutable; or
- You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
Read the rest at the sourceFrom Stack Overflow: asked by bitbonk, answered by Jon Skeet (CC BY-SA 4.0)
DateTime vs DateTimeOffset
DateTimeOffsetis a representation of instantaneous time (also known as absolute time). By that, I mean a moment in time that is universal for everyone (not accounting for leap seconds, or the relativistic effects of time dilation). Another way to represent instantaneous time is with aDateTimewhere.KindisDateTimeKind.Utc.This is distinct from calendar time (also known as civil time), which is a position on someone's calendar, and there are many different calendars all over the globe. We call these calendars time zones. Calendar time is represented by a
DateTimewhere.KindisDateTimeKind.Unspecified, orDateTimeKind.Local. And.Localis only meaningful in scenarios where you have an implied understanding of where the computer that is using the result is positioned. (For example, a user's workstation)So then, why
DateTimeOffsetinstead of a UTCDateTime? It's all about perspective. Let's use an analogy - we'll pretend to be photographers.Imagine you are standing on a calendar timeline, pointing a camera at a person on the instantaneous timeline laid out in front of you. You line up your camera according to the rules of your timezone - which change periodically due to daylight saving time, or due to other changes to the legal definition of your time zone. (You don't have a steady hand, so your camera is shaky.)
The person standing in the photo would see the angle at which your camera came from. If others were taking pictures, they could be from different angles. This is what the
Offsetpart of theDateTimeOffsetrepresents.So if you label your camera "Eastern Time", sometimes you are pointing from -5, and sometimes you are pointing from -4. There are cameras all over the world, all labeled different things, and all pointing at the same instantaneous timeline from different angles. Some of them are right next to (or on top of) each other, so just knowing the offset isn't enough to determine which timezone the time is related to.
And what about UTC? Well, it's the one camera out there that is guaranteed to have a steady hand. It's on a tripod, firmly anchored into the ground. It's not going anywhere. We call its angle of perspective the zero offset.
So - what does this analogy tell us? It provides some intuitive guidelines-
Read the rest at the sourceFrom Stack Overflow: asked by David Reis, answered by Matt Johnson-Pint (CC BY-SA 4.0)
Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction
Html.Partialreturns a String.Html.RenderPartialcallsWriteinternally and returnsvoid.The basic usage is:
// Razor syntax @Html.Partial("ViewName") @{ Html.RenderPartial("ViewName"); } // WebView syntax <%: Html.Partial("ViewName") %> <% Html.RenderPartial("ViewName"); %>In the snippet above, both calls will yield the same result.
While one can store the output of
Html.Partialin a variable or return it from a method, one cannot do this withHtml.RenderPartial.The result will be written to the
Responsestream during execution/evaluation.This also applies to
Html.ActionandHtml.RenderAction.From Stack Overflow: asked by Ghooti Farangi, answered by GvS (CC BY-SA 4.0)
What is the difference between .NET Core and .NET Standard Class Library project types?
When should we use one over the other?
The decision is a trade-off between compatibility and API access.
Use a .NET Standard library when you want to increase the number of applications that will be compatible with your library, and you are okay with a decrease in the .NET API surface area your library can access.
Use a .NET Core library when you want to increase the .NET API surface area your library can access, and you are okay with allowing only .NET Core applications to be compatible with your library.
For example, a library that targets .NET Standard 1.3 will be compatible with applications that target .NET Framework 4.6, .NET Core 1.0, Universal Windows Platform 10.0, and any other platform that supports .NET Standard 1.3. The library will not have access to some parts of the .NET API, though. For instance, the
Microsoft.NETCore.CoreCLRpackage is compatible with .NET Core, but not with .NET Standard.What is the difference between Class Library (.NET Standard) and Class Library (.NET Core)?
Compatibility: Libraries that target .NET Standard will run on any .NET Standard compliant runtime, such as .NET Core, .NET Framework, Mono/Xamarin. On the other hand, libraries that target .NET Core can only run on the .NET Core runtime.
API Surface Area: .NET Standard libraries come with everything in
NETStandard.Library, whereas .NET Core libraries come with everything inMicrosoft.NETCore.App. The latter includes approximately 20 additional libraries, some of which we can add manually to our .NET Standard library (such asSystem.Threading.Thread) and some of which are not compatible with the .NET Standard (such asMicrosoft.NETCore.CoreCLR).Also, .NET Core libraries specify a runtime and come with an application model. That's important, for instance, to make unit test class libraries runnable.
Why do both exist?
Ignoring libraries for a moment, the reason that .NET Standard exists is for portability; it defines a set of APIs that .NET platforms agree to implement. Any platform that implements a .NET Standard is compatible with libraries that target that .NET Standard. One of those compatible platforms is .NET Core.
Coming back to libraries, the .NET Standard library templates exist to run on multiple runtimes (at the expense of API surface area). Conversely, the .NET Core library templates exist to access more API surface area (at the expense of compatibility) and to specify a platform against which to build an executable.
Here is an interactive matrix that shows which .NET Standard supports which .NET implementation(s) and how much API surface area is available.
From Stack Overflow: asked by Gigi, answered by Shaun Luttin (CC BY-SA 4.0)
Is there a way to check if a file is in use?
Updated NOTE on this solution: Checking with
FileAccess.ReadWritewill fail for Read-Only files so the solution has been modified to check withFileAccess.Read.ORIGINAL: I've used this code for the past several years, and I haven't had any issues with it.
Understand your hesitation about using exceptions, but you can't avoid them all of the time:
protected virtual bool IsFileLocked(FileInfo file) { try { using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None)) { stream.Close(); } } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } //file is not locked return false; }From Stack Overflow: asked by Dawsy, answered by ChrisW (CC BY-SA 4.0)
When to use .First and when to use .FirstOrDefault with LINQ?
I would use
First()when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.Use
FirstOrDefault()when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).Finally, the difference between
First()andTake(1)is thatFirst()returns the element itself, whileTake(1)returns a sequence of elements that contains exactly one element.From Stack Overflow: asked by Metro Smurf, answered by driis (CC BY-SA 4.0)
What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?
AssemblyVersion
Where other assemblies that reference your assembly will look. If this number changes, other assemblies must update their references to your assembly! Only update this version if it breaks backward compatibility. The
AssemblyVersionis required.I use the format: major.minor (and major for very stable codebases). This would result in:
[assembly: AssemblyVersion("1.3")] // in AssemblyInfo.cs <AssemblyVersion>1.3</AssemblyVersion> // in .csprojIf you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.
AssemblyFileVersion
Used for deployment (like setup programs). You can increase this number for every deployment. Use it to mark assemblies that have the same
AssemblyVersionbut are generated from different builds and/or code.In Windows, it can be viewed in the file properties.
The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.
I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:
[assembly: AssemblyFileVersion("1.3.2.42")] // in AssemblyInfo.cs <FileVersion>1.3.2.42</FileVersion> // in .csprojBe aware that System.Version names these parts as
major.minor.build.revision!AssemblyInformationalVersion
The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.
The
AssemblyInformationalVersionis optional. If not given, the AssemblyFileVersion is used.I use the format: major.minor[.patch] [revision as string]. This would result in:
[assembly: AssemblyInformationalVersion("1.3 RC1")] // in AssemblyInfo.cs <InformationalVersion>1.3 RC</InformationalVersion> // in .csprojVersion (or VersionPrefix and VersionSuffix)
You can now also use
<Version>(or<VersionPrefix>and<VersionSuffix>) in your project file.This will be used for AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion if they are not specified. It will also be used for the NuGet Package version!
For example:
<Version>1.3.2-beta</Version> // or <VersionPrefix>1.3.2</VersionPrefix> <VersionSuffix>beta</VersionSuffix>Which will result into:
NuGetPackageVersion : 1.3.2-beta AssemblyVersion: 1.3.2.0 AssemblyFileVersion: 1.3.2.0 AssemblyInformationalVersion: 1.3.2-betaFrom Stack Overflow: asked by Jakub Šturc, answered by Remy van Duijkeren (CC BY-SA 4.0)
What's the difference between struct and class in .NET?
In .NET, there are two categories of types, reference types and value types.
Structs are value types and classes are reference types.
The general difference is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.
A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.
A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.
This has one benefit, to begin with:
- value types always contains a value
- reference types can contain a null-reference, meaning that they don't refer to anything at all at the moment
Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:
- copying the contents of a value type variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other
- copying the contents of a reference type variable into another variable, copies the reference, which means you now have two references to the same somewhere else storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places
When you declare variables or fields, here's how the two types differ:
- variable: value type lives on the stack, reference type lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note Eric Lipperts article series: The Stack Is An Implementation Detail.)
- class/struct-field: value type lives completely inside the type, reference type lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.
From Stack Overflow: asked by Keith, answered by Lasse V. Karlsen (CC BY-SA 3.0)
Deep cloning objects
Whereas one approach is to implement the
ICloneableinterface (described here, so I won't regurgitate), here's a nice deep clone object copier I found on The Code Project a while ago and incorporated it into our code. As mentioned elsewhere, it requires your objects to be serializable.using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; /// <summary> /// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx /// Provides a method for performing a deep copy of an object. /// Binary Serialization is used to perform the copy. /// </summary> public static class ObjectCopier { /// <summary> /// Perform a deep copy of the object via serialization. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>A deep copy of the object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", nameof(source)); } // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(source, null)) return default; using var stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } }The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too complex.
In case of you prefer to use the new extension methods of C# 3.0, change the method to have the following signature:
public static T Clone<T>(this T source) { // ... }Now the method call simply becomes
objectBeingCloned.Clone();.EDIT (January 10 2015) Thought I'd revisit this, to mention I recently started using (Newtonsoft) Json to do this, it should be lighter, and avoids the overhead of [Serializable] tags. (NB @atconway has pointed out in the comments that private members are not cloned using the JSON method)
/// <summary> /// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T CloneJson<T>(this T source) { // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(source, null)) return default; // initialize inner objects individually // for example in default constructor some list property initialized with some values, // but in 'source' these items are cleaned - // without ObjectCreationHandling.Replace default constructor values will be added to result var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace}; return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings); }From Stack Overflow: asked by NakedBrunch, answered by johnc (CC BY-SA 4.0)
Catch multiple exceptions at once?
Catch
System.Exceptionand switch on the typescatch (Exception ex) { if (ex is FormatException || ex is OverflowException) { WebId = Guid.Empty; } else throw; }From Stack Overflow: asked by Michael Stum, answered by Joseph Daigle (CC BY-SA 4.0)
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
Contrary to the answers here, you DON'T need to worry about encoding if the bytes don't need to be interpreted!
Like you mentioned, your goal is, simply, to "get what bytes the string has been stored in".
(And, of course, to be able to re-construct the string from the bytes.)For those goals, I honestly do not understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.
Just do this instead:
static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } // Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); }As long as your program (or other programs) don't try to interpret the bytes somehow, which you obviously didn't mention you intend to do, then there is nothing wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.
Additional benefit to this approach: It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!
It will be encoded and decoded just the same, because you are just looking at the bytes.
If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters.
From Stack Overflow: asked by Agnel Kurian, answered by user541686 (CC BY-SA 4.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-SA12 questions