EzDevInfo.com

.net interview questions

Top .net frequently asked interview questions

How to escape braces (curly brackets) in a format string in .NET

How can brackets be escaped in using string.Format. For example:

String val = "1,2,3"
String.Format(" foo {{0}}", val); 

This example doesn't throw an exception, but outputs the string foo {0}

Is there a way to escape the brackets?


Source: (StackOverflow)

Sending email in .NET through Gmail

Instead of relying on my host to send email, I was thinking of sending the messages though my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do?


Source: (StackOverflow)

Advertisements

How do I calculate someone's age in C#?

Given a DateTime representing a person's birthday, how do I calculate their age?


Source: (StackOverflow)

Should 'using' statements be inside or outside the namespace?

I have been running StyleCop over some C# code, and it keeps reporting that my using statements should be inside the namespace.

Is there a technical reason for putting the using statements inside instead of outside the namespace?


Source: (StackOverflow)

Deep cloning objects

I want to do something like:

MyObject myObj = GetMyObj(); // Create and fill a new object
MyObject newObj = myObj.Clone();

And then make changes to the new object that are not reflected in the original object.

I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.

How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?


Source: (StackOverflow)

How do I enumerate an enum?

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit {
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod() {
    foreach (Suit suit in Suit) {
        DoSomething(suit);
    }
}

And gives the compile time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.


Source: (StackOverflow)

Group By Multiple Columns

How can I do GroupBy Multiple Columns in LINQ

Something similar to this in SQL:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>

How can I convert this to LINQ:

QuantityBreakdown
(
    MaterialID int,
    ProductID int,
    Quantity float
)

INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID

Source: (StackOverflow)

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

In ASP.NET MVC, what is the difference between:

  • Html.Partial and Html.RenderPartial
  • Html.Action and Html.RenderAction

Source: (StackOverflow)

Difference between Decimal, Float and Double in .NET?

What is the difference between Decimal, Float and Double in .NET?

When would someone use one of these?


Source: (StackOverflow)

Converting a string to byte-array without using an encoding (byte-by-byte)

How do I convert a string to a byte[] in .NET (C#)?

Also, why should encoding be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?


Source: (StackOverflow)

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

There are three assembly version attributes. What are differences? Is it ok if I use AssemblyVersion and ignore the rest?


MSDN says:

  • AssemblyVersion:

    Specifies the version of the assembly being attributed.

  • AssemblyFileVersion:

    Instructs a compiler to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number.

  • AssemblyInformationalVersion:

    Defines additional version information for an assembly manifest.


This is follow up to What are the best practices for using Assembly Attributes?


Source: (StackOverflow)

Proper use of the IDisposable interface

I know from reading the MSDN documentation that the "primary" use of the IDisposable interface is to clean up unmanaged resources.

To me, "unmanaged" means things like database connections, sockets, window handles, etc. But, I've seen code where the Dispose method is implemented to free managed resources, which seems redundant to me, since the garbage collector should take care of that for you.

For example:

public class MyCollection : IDisposable
{
    private List<String> _theList = new List<String>();
    private Dictionary<String, Point> _theDict = new Dictionary<String, Point>();

    // Die, clear it up! (free unmanaged resources)
    public void Dispose()
    {
        _theList.clear();
        _theDict.clear();
        _theList = null;
        _theDict = null;
    }

My question is, does this make the garbage collector free memory used by MyCollection any faster than it normally would?

edit: So far people have posted some good examples of using IDisposable to clean up unmanaged resources such as database connections and bitmaps. But suppose that _theList in the above code contained a million strings, and you wanted to free that memory now, rather than waiting for the garbage collector. Would the above code accomplish that?


Source: (StackOverflow)

Try-catch speeding up my code?

I wrote some code for testing the impact of try-catch, but seeing some surprising results.

static void Main(string[] args)
{
    Thread.CurrentThread.Priority = ThreadPriority.Highest;
    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;

    long start = 0, stop = 0, elapsed = 0;
    double avg = 0.0;

    long temp = Fibo(1);

    for (int i = 1; i < 100000000; i++)
    {
        start = Stopwatch.GetTimestamp();
        temp = Fibo(100);
        stop = Stopwatch.GetTimestamp();

        elapsed = stop - start;
        avg = avg + ((double)elapsed - avg) / i;
    }

    Console.WriteLine("Elapsed: " + avg);
    Console.ReadKey();
}

static long Fibo(int n)
{
    long n1 = 0, n2 = 1, fibo = 0;
    n++;

    for (int i = 1; i < n; i++)
    {
        n1 = n2;
        n2 = fibo;
        fibo = n1 + n2;
    }

    return fibo;
}

On my computer, this consistently prints out a value around 0.96..

When I wrap the for loop inside Fibo() with a try-catch block like this:

static long Fibo(int n)
{
    long n1 = 0, n2 = 1, fibo = 0;
    n++;

    try
    {
        for (int i = 1; i < n; i++)
        {
            n1 = n2;
            n2 = fibo;
            fibo = n1 + n2;
        }
    }
    catch {}

    return fibo;
}

Now it consistently prints out 0.69... -- it actually runs faster! But why?

Note: I compiled this using the Release configuration and directly ran the EXE file (outside Visual Studio).

EDIT: Jon Skeet's excellent analysis shows that try-catch is somehow causing the x86 CLR to use the CPU registers in a more favorable way in this specific case (and I think we're yet to understand why). I confirmed Jon's finding that x64 CLR doesn't have this difference, and that it was faster than the x86 CLR. I also tested using int types inside the Fibo method instead of long types, and then the x86 CLR was as equally fast as the x64 CLR.


UPDATE: It looks like this issue has been fixed by Roslyn. Same machine, same CLR version -- the issue remains as above when compiled with VS 2013, but the problem goes away when compiled with VS 2015.


Source: (StackOverflow)

How to update the GUI from another thread in C#?

What is the simplest way to update a Label from another thread?

I have a Form on thread1, from that I'm starting another thread (thread2). While thread2 is processing some files I would like to update a Label on the Form with the current status of thread2's work.

How can I do that?


Source: (StackOverflow)