c sharp Faqs

body { font-size: 84%; }

var doImage=doImage;var TType=TType;
function mhHover(tbl,idx,cls){var t,d;if(document.getElementById)t=document.getElementById(tbl);else t=document.all(tbl);if(t==null)return;if(t.getElementsByTagName)d=t.getElementsByTagName(“TD”);else d=t.all.tags(“TD”);if(d==null)return;if(d.length<=idx)return;d[idx].className=cls;}


C# Frequently Asked Questions

The C# team posts answers to common questions

  • How do I use an alias for a namespace or class?

    Use the using directive to create an alias for a long namespace or class name.
    You can then use it anywhere you normally would have used that class or
    namespace. The using alias has a scope within the namespace you declare it in. Sample code:

    // Namespace: 
    using act = System.Runtime.Remoting.Activation; 
    // Class: 
    using list = System.Collections.ArrayList; 
    list l = new list(); // Creates an ArrayList 
    act.UrlAttribute foo; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute foo

    [Author: Jon Skeet]

  • What’s the difference between override and new?

    This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of
    the object that the reference refers to is used to decide which method implementation to use. When a method
    of a base class is overridden in a derived class, the version in the derived class is used, even if the calling
    code didn’t “know” that the object was an instance of the derived class. For instance:

    public class Base 
        public virtual void SomeMethod() 
    public class Derived : Base 
        public override void SomeMethod() 
    Base b = new Derived(); 

    will end up calling Derived.SomeMethod if that overrides Base.SomeMethod. Now,
    if you use the new keyword instead of override, the method in the derived class
    doesn’t override the method in the base class, it merely hides it. In that case, code like this:

    public class Base 
        public virtual void SomeOtherMethod() 
    public class Derived : Base 
        public new void SomeOtherMethod() 
    Base b = new Derived(); 
    Derived d = new Derived(); 

    Will first call Base.SomeOtherMethod (line 3), then Derived.SomeOtherMethod (line 4).
    They’re effectively two entirely separate methods which happen to have the same name, rather than the derived method
    overriding the base method.

    If you don’t specify either new or overrides, the resulting output is the same
    as if you specified new, but you’ll also get a compiler warning (as you may not be aware that you’re
    hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to
    include the keyword).

    That provides the basics of overriding and the difference between new and override,
    but you should really see a book or tutorial for a more in-depth look at polymorphism.

    [Author: Jon Skeet]

  • Why doesn’t C# have checked exceptions?

    Checked exceptions are a very hotly debated topic in some circles, particularly for experienced Java developers moving to, or additionally learning, C#. Here are some resources that discuss the issue in depth:

    Note that without the CLR itself supporting checked exceptions, it would be effectively impossible for C# to do so alone.
    [Author: Jon Skeet]

  • What’s the difference between cast syntax and using the as operator?

    Using the as operator differs from a cast in C# in three important ways:

    1. It returns null when the variable you are trying to convert is not of
      the requested type or in it’s inheritance chain, instead of throwing an exception.
    2. It can only be applied to reference type variables converting to reference types.
    3. Using as will not perform user-defined conversions, such as implicit or
      explicit conversion operators, which casting syntax will do.

    There are in fact two completely different operations defined in IL that
    handle these two keywords (the castclass and
    isinst instructions) – it’s not
    just “syntactic sugar” written by C# to get this different behavior. The
    as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft’s
    CLR compared to casting (even in cases where there are no invalid casts
    which would severely lower casting’s performance due to exceptions).

    [Author: Jon Skeet]

  • What’s the difference between string and System.String?

    C# defines a number of aliases for CLR types. They may be used interchangably, and even mixed together, e.g.
    string x = new System.String(' ', 5);.
    These are the aliases defined:

    Alias CLR type
    string System.String
    sbyte System.SByte
    byte System.Byte
    short System.Int16
    ushort System.UInt16
    int System.Int32
    uint System.UInt32
    long System.Int64
    ulong System.UInt64
    char System.Char
    float System.Single
    double System.Double
    bool System.Boolean
    decimal System.Decimal

    [Author: Jon Skeet]

  • What’s the difference between an event and a delegate?

    Put simply, an event gives more limited access than a delegate. If an event is made public, code in
    other classes can only add or remove handlers for that event; they can’t necessarily fire it, find out
    all the handlers for it, or remove handlers they don’t know about. Events also allow more flexibility in
    terms of how the handlers are stored. For more details on this, see
    Gunnerson’s article on the topic

    [Author: Jon Skeet]

  • Why can’t I use static and const together?

    All constants declarations are implicitly static, and the C# specification states that the
    (redundant) inclusion of the static modifier is prohibited. I believe this is to avoid the
    confusion which could occur if a reader were to see two constants, one declared static and one not – they
    could easily assume that the difference in specification implied a difference in semantics. Having said
    that, there is no prohibition on redundantly specifying an access modifier which is also the default one,
    where there is a choice. For instance, a (concrete) method can be explicitly marked as private despite that being the
    default. The rule appears to be that where there is no choice (e.g. a method declaration in an interface)
    the redundant modifier is prohibited. Where there is a choice, it’s allowed.

    [Author: Jon Skeet]

  • What character escape sequences are available?

    C# defines the following character escape sequences:

    • \' – single quote, needed for character literals
    • \" – double quote, needed for string literals
    • \\ – backslash
    • – Unicode character 0
    • \a – Alert (character 7)
    • \b – Backspace (character 8)
    • \f – Form feed (character 12)
    • \n – New line (character 10)
    • \r – Carriage return (character 13)
    • \t – Horizontal tab (character 9)
    • \v – Vertical quote (character 11)
    • \uxxxx – Unicode escape sequence for character with hex value xxxx
    • \xn[n][n][n] – Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
    • \Uxxxxxxxx – Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)

    Of these, \a, \f, \v, \x and \U are rarely used in my experience.

    [Author: Jon Skeet]

  • What does an @ before the start of a string literal mean?

    A string literal such as @"c:\Foo" is called a verbatim string literal. It basically means,
    “don’t apply any interpretations to characters until the next quote character is reached”. So, a verbatim
    string literal can contain backslashes (without them being doubled-up) and even line separators. To get a
    double-quote (") within a verbatim literal, you need to just double it, e.g.
    @"My name is ""Jon""" represents the string My name is "Jon". Verbatim string literals
    which contain line separators will also contain the white-space at the start of the line, so I tend
    not to use them in cases where the white-space matters. They’re very handy for including XML or SQL in your source
    code though, and another typical use (which doesn’t need line separators) is for specifying a file system path.

    It’s worth noting that it doesn’t affect the string itself in any way: a string specified as a verbatim string literal
    is exactly the same as a string specified as a normal string literal with appropriate escaping. The debugger will
    sometimes choose to display a string as a verbatim string literal – this is solely for ease of viewing the string’s
    contents without worrying about escaping.

    [Author: Jon Skeet]

  • How are parameters passed in C#? Are they passed by reference or by value?

    By default, all parameters are passed by value in C#. Parameters are only passed by reference if you explicitly include
    an out or ref modifier. However, you need to be aware that when the type of the
    parameter is a reference type, you’re passing a reference rather than an actual object. For more information, see my
    article on parameter passing and
    the C#
    Programmer’s Reference

    [Author: Jon Skeet]

  • Does C# have templates like C++?

    Although C# doesn’t have templates, and isn’t likely to get them, it is
    getting a feature called generics which will be available in the next version
    of .NET and Visual Studio. Generics will be a feature in the CLR itself,
    and most languages targetting the CLR will change to support it. Generics provide a
    lot of the functionality of C++ templates (mostly in terms of type safety) but in a more
    restricted (and therefore potentially less confusing) way.

    For more information, see:

    [Author: Jon Skeet]

  • Why doesn’t C# have VB.NET’s ‘with’ operator?

    Many people, including the C# language designers, believe that ‘with’ often harms readability, and is more of a curse than a blessing. It is clearer to declare a local variable with a meaningful name, and use that variable to perform multiple operations on a single object, than it is to have a block with a sort of implicit context.
    For more information, see the Ask a C# Language Designer page.
    [Author: Jon Skeet]
  • What are the advantages of C# over VB.NET and vice versa?

    The choice between C# and VB.NET is largely one of subjective
    preference. Some people like C#’s terse syntax, others like VB.NET’s
    natural language, case-insensitive approach. Both have access to the same
    framework libraries. Both will perform largely equivalently (with a few
    small differences which are unlikely to affect most people, assuming
    VB.NET is used with Option Strict on). Learning the .NET framework itself is
    a much bigger issue than learning either of the languages, and it’s perfectly possible
    to become fluent in both – so don’t worry too much about which to plump for. There are,
    however, a few actual differences which may affect your decision:

    VB.NET Advantages
    • Support for optional parameters – very handy for some COM interoperability
    • Support for late binding with Option Strict off – type safety at compile time
      goes out of the window, but legacy libraries which don’t have strongly typed interfaces
      become easier to use.
    • Support for named indexers (aka properties with parameters).
    • Various legacy VB functions (provided in the Microsoft.VisualBasic namespace, and can be
      used by other languages with a reference to the Microsoft.VisualBasic.dll). Many of
      these can be harmful to performance if used unwisely, however, and many people believe they should
      be avoided for the most part.
    • The with construct: it’s a matter of debate as to whether this is an advantage or not,
      but it’s certainly a difference.
    • Simpler (in expression – perhaps more complicated in understanding) event handling, where
      a method can declare that it handles an event, rather than the handler having to be set up in code.
    • The ability to implement interfaces with methods of different names. (Arguably this makes it harder
      to find the implementation of an interface, however.)
    • Catch ... When ... clauses, which allow exceptions to be filtered based on runtime expressions
      rather than just by type.
    • The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an
      advantage for small projects, people creating very large projects have found that the IDE slows down considerably
      as the project gets larger.
    C# Advantages
    • XML documentation generated from source code comments. (This is coming in VB.NET with
      Whidbey (the code name for the next version of Visual Studio and .NET), and there are tools which will do it with existing VB.NET code
    • Operator overloading – again, coming to VB.NET in Whidbey.
    • Language support for unsigned types (you can use them from VB.NET, but they aren’t in the language
      itself). Again, support for these is coming to VB.NET in Whidbey.
    • The using statement, which makes unmanaged resource disposal simple.
    • Explicit interface implementation, where an interface which is already implemented in a base class
      can be reimplemented separately in a derived class. Arguably this makes the class harder to understand,
      in the same way that member hiding normally does.
    • Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations.
      However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).
      Note that unsafe code is still managed code, i.e. it is compiled to IL, JITted, and run within the CLR.

    Despite the fact that the above list appears to favour VB.NET (if you don’t mind waiting for Whidbey),
    many people prefer C#’s terse syntax enough to make them use C# instead.

    [Author: Jon Skeet]

  • Where is the C# specification?

    There are two versions of the C# specification – one from Microsoft, and one from ECMA. They are the same in all important respects (a few pieces of explanatory wording are different, but nothing that affects the specification itself) but the numbering of sections is different.

    The ECMA specification is available as a PDF, or you can email ECMA and they will send you a hard copy for free. Details are on the ECMA website. Alternatively, Jon Jagger’s HTML version is available and is a useful download. It is from a draft version, but it’s very close to the final version. I don’t know whether or not Jon Jagger is planning to make an HTML copy of version 2 of the specification when it’s released.

    The Microsoft version is available online or within the offline version of the MSDN – look for “specifications, Visual C#” in the index to find it quickly.

  • Why don’t relational operators return bool as a type?

    Section 10.9.2 of the language specification says:

    A binary operator must take two parameters, at least one of which must have the class or struct type in which the operator is declared. Parameters of the shift operators (§7.8) are further constrained. A binary operator can return any type.

    Why isn’t it limited to just returning bool?

    There is some weirdness here because of the C# ability to support nullable types, such as the SQL types (ie SQLInt32, SQLSingle, etc.). These type can either have a value or be null.

    One of the strange features of the SQL expression syntax is if either operand in a binary operation is null, the result is null. So, when we want to write the comparison operator for SQLInt32, we have a problem if the result type is constrained to bool, since null is neither true or false.

    C# therefore allows the comparison operators to return another type as long as the resulting type has operator true and operator false defined. That gives us enough support to be able to write:

    SQLInt32 x = …;

    SQLInt32 y = …;

    if (x == y)


        // x and y or equal


    else if (x != y)


        // x and y are not equal




        // the result of the comparison is null



    Which allows the full richness of SQL types to be expressed.

    Author: Eric Gunnerson]

©2005 Microsoft Corporation. All rights reserved. Terms of Use |Trademarks |Privacy Statement

var bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl05_Ratings=new RateControl(‘bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl05_Ratings’,’bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl05_Ratings’,’bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl05_Ratings_Value’, 5, ‘/Themes/default/images/common/’, false, ‘CommonRateControl’,’CommonRateControlActive’,’CommonRateControlReadOnly’,[‘Terrible’,’Poor’,’Fair’,’Average’,’Good’,’Excellent’],true,false);var bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl13_Ratings=new RateControl(‘bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl13_Ratings’,’bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl13_Ratings’,’bp___v___ctl00_ctl00_bcr_r___postlist___EntryItems_ctl13_Ratings_Value’, 5, ‘/Themes/default/images/common/’, false, ‘CommonRateControl’,’CommonRateControlActive’,’CommonRateControlReadOnly’,[‘Terrible’,’Poor’,’Fair’,’Average’,’Good’,’Excellent’],true,false);

C sharp Faqs

C# Frequently Asked Questions

The C# team posts answers to common questions

  • When should I use == and when should I use Equals?

    The Equals method is just a virtual one defined in System.Object, and overridden
    by whichever classes choose to do so. The == operator is an operator which can be overloaded
    by classes, but which usually has identity behaviour.For reference types where == has not been overloaded, it compares whether two references
    refer to the same object – which is exactly what the implementation of Equals does in
    System.Object.Value types do not provide an overload for == by default.
    However, most of the value types provided by the framework provide their
    own overload. The default implementation of Equals for a value
    type is provided by ValueType, and uses reflection
    to make the comparison, which makes it significantly slower than a
    type-specific implementation normally would be. This implementation also
    calls Equals on pairs of references within the two values
    being compared.However, the main difference between the two types of comparison in
    normal use (where you’re unlikely to be defining your own value types
    very often) is polymorphism. Operators are overloaded, not overridden,
    which means that unless the compiler knows to call the more specific
    version, it’ll just call the identity version. To illustrate that, here’s
    an example:

    using System;public class Test{static void Main(){// Create two equal but distinct strings
    string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
    string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
    Console.WriteLine (a==b);
    Console.WriteLine (a.Equals(b));
    // Now let's see what happens with the same tests but
    // with variables of type object
    object c = a;
    object d = b;
    Console.WriteLine (c==d);
    Console.WriteLine (c.Equals(d));

    The results are:


    The third line is False because the compiler can only call the non-overloaded version of ==
    as it doesn’t know that the contents of c and d are both string references. As they
    are references to different strings, the identity operator returns false.

    So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals
    when you want to test equality rather than reference identity. The exception is for strings – comparing strings with
    == does make things an awful lot simpler and more readable but you need to remember that both
    sides of the operator must be expressions of type string in order to get the comparison to work properly.

    For value types, I’d normally use == for easier-to-read code. Things would get tricky if a value type
    provided an overload for == which acted differently to Equals, but I’d consider such a type
    very badly designed to start with.

    [Author: Jon Skeet]

  • Should I assign null to my local variables?

    Q: Should I assign null to my local variables after I use them?
    For example:
    string s = …;
    s = null;A: There is rarely a need to do this for local variables in C#
    The lifetime of variables is tracked by the JIT – it analyzes how variables are used in a routine, and it knows exactly when the variable is no longer needed, and after that point, the value is available to be collected.
    Interestingly, if you assign it to null, you are actually extending the lifetime of the variable slightly, so it could cause it to be garbage collected later (though realistically, there’s unlikely to be any real difference here.
    This is true for the vast majority of methods. If you have a method where your code lives for a while – a loop on a separate thread, for example – then it may be worthwhile to see if there are any unnecessary values living in variables while you wait.[Author: Eric Gunnerson]
  • Why do I need a null test before I invoke a delegate?

    Q: Why do I need a null test before I invoke a delegate?
    A: If you have an event in a class, you need to add a null test before you call the delegate. Typically, you would write:

    if (Click != null)    Click(arg1, arg2);

    There is actually a possible race condition here – the event can be cleared between the first and second line. You would actually want to write:

    ClickHandler handler = Click;if (handler != null)    handler(arg1, arg2);

    usually. You might want to do some other sort of synchronization in other scenarios.
    So back to the main question. Why is the null test required?
    We can’t change the existing behavior of calling through a delegate as some apps may depend on it, so it would have to be an addition to the language.
    We have talked about adding an Invoke() keyword to the language to make this easier, but after a fair bit of discussion, we decided that we couldn’t do the right thing all the time, so we elected not to do anything.
    [Author: Eric Gunnerson]

  • Why doesn’t C# warn about unused methods?

    Q: Why doesn’t C# warn on unused methods?
    A: This is something that the C# compiler could do, subject to a few caveats:

    • Virtual functions would have to be excluded
    • Interface implementations wouldn have to be excluded
    • You would get false positives if you used reflection
    • You might get false positives if you used delegates (the compiler might be able to be smart here)

    Other than that, it would be possible for us to do this, and we may do it in a future version.

    [Author: Eric Gunnerson]

  • How can I update my user interface from a thread that did not create it?

    When performing any action on a control which requires the updating of a user interface element (e.g. setting the Text property on almost any class derived from Control, updating the data source behind a DataGrid), these operations MUST take place on the thread that created the UI element.
    In order to do this, the Control class provides the Invoke method, which will take a delegate and execute it on the thread that the UI element was created on. In order to use this, one must declare a function that performs the UI operation. For example, say a form has a TextBox on it named m_TextBox. To update the text from another thread, create a method that will update the Text property on the TextBox:

    // The declaration of the textbox. private TextBox m_TextBox;// Updates the textbox text. private void UpdateText(string text){// Set the textbox text.   m_TextBox.Text = text; }

    Now, create a delegate that has the same signature as the method that was previously defined:

    public delegate void UpdateTextCallback(string text);

    In your thread, you can call the Invoke method on m_TextBox, passing the delegate to call, as well as the parameters.

    m_TextBox.Invoke(new UpdateTextCallback(this.UpdateText),            new object[]{”Text generated on non-UI thread.”});

    Note: Do not create a method that matches the EventHandler delegate signature and pass that. The implementation of Invoke on the Control class will not take into account the parameters passed to Invoke if the type of the delegate is EventHandler. It will pass the control that Invoke was called on for the sender parameter as well as the value returned by EventArgs.Empty for the e parameter.
    [Author: Nicholas Paldino]

  • Why can’t I have static and instance methods with the same name?

    Q: Why can’t I have static and instance methods with the same name?

    class Test{static void Process();void Process();void AmbiguousCaller() { Process(); }

    there’s no ambiguity, since the first can only be called through the type name, and the second can only be called through an instance.
    It is true that there would be no ambiguity between the two functions as far as a compiler is concerned. There would, however, be a considerable potential for confusion on the part of the user. It would be tough to find the right method in documentation, and once you did, hard to be sure that you are calling the right version (ie you could accidentally call the static version when you wanted the instance version).
    We therefore prohibit this case.
    [Author: Eric Gunnerson]

  • Where can I find sample C# code for simple threading?

    Refer to the System.Threading namespace on MSDN for full details. Meanwhile here is a quick taste.

    using System;using System.Threading;class ThreadTest{public void Runme(){
    Console.WriteLine("Runme Called");
    public static void Main(String[] args)
    ThreadTest b = new ThreadTest();
    Thread t = new Thread(new ThreadStart(b.Runme));
    Console.WriteLine("Thread 't' started.");
            Console.WriteLine("There is no telling when " +
                              "'Runme' will be invoked. ");
    Console.WriteLine("Thread 't' has ended.");
    [Author: Santosh Zachariah]
  • How do C# generics compare to C++ templates?

    Q: How do C# generics compare to C++ templates?
    A: This is really a fairly complex topic.
    Anders has touched on it in an interview.
    I should state at the outset that the goals of generics are not the same as the goals of templates. There are some things that templates do better than generics, and vice versa.
    C++ templates use a compile-time model. When a template is used in a C++ program, the effect is as if a sophisticated macro processor had been used.
    C# generics are not just a feature of the compiler, but also a feature of the runtime. A generic type such as List<T> maintains its generic-ness (genericity) after it has been compiled. Or, to look at it another way, the substitution that the C++ compiler does at compile time is done at JIT time in the C# generic world.
    Error Checking
    Error is best illustrated through an example. Consider a template that has a method like this;
    T Add(T t1, Tt2)
    return t1 + t2;
    the C++ compiler will be able to parse this method successfully. When this template is actually used, the Ts will be replaced with an actual type. If a type such as int is used, the compiler will be able to create the Add method correctly, as it knows how to add two ints.
    If a type such as Employee was used, the compiler would issue an error, as the compiler would know that there was no way to add two Employees.
    The generics world is very different. Because the type that is used with the generic is not known at compile time, the compiler needs additional information about the type that will be used with a generic class.
    This is done through constraints, which allow the author to constrain the types that can be used with a generic type.
    For example:
    Class List<T> where T:IComparable
    means that whenever I use a T in my implementation, I can call the CompareTo() function on it.
    Constraints could theoretically provide nearly the same level of flexibility that templates do, but that would require a very complex constraint syntax. For the Whidbey release, only certain operations can be specified through contraints, which limits the number of operations you can perform.
    For example, there is no way to say that a generic type must have an add operator, so you can’t write “a + b“ in a generic class.
    It is possible to work around this at runtime using reflection, but the implementation isn’t as clean and there may be a performance loss. We may address some of these issues in future releases
    Run-time operations
    Generics in C# have full run-time support. If you use reflection, you will find that you can reflect over generic types, and create them at runtime. There’s no real analog of this in the C++ world.
    Space Use
    The use of space is different between C++ and C#. Because C++ templates are done at compile time, each use of a different type in a template results in a separate chunk of code being created by the compiler.
    In the C# world, it’s somewhat different. The actual implementations using a specific type are created at runtime. When the runtime creates a type like List<int>, the JIT will see if that has already been created. If it has, it merely users that code. If not, it will take the IL that the compiler generated and do appropriate replacements with the actual type.
    That’s not quite correct. There is a separate native code path for every value type, but since reference types are all reference-sized, they can share their implementation.
    This means that the C# approach should have a smaller footprint on disk, and in memory, so that’s an advantage for generics over C++ templates.
    In fact, the C++ linker implements a feature known as “template folding“, where the linker looks for native code sections that are identical, and if it finds them, folds them together. So it’s not a clear-cut as it would seem to be.
    Template metaprogramming
    C++ templates are sometimes used for a technique known as template metaprogramming. There is no way to do this in C#.
    [Author: Eric Gunnerson]
  • Where can I get a full comparison between C# and VB.NET?

    Microsoft provides a very full
    page which compares not only C# and VB.NET, but also other languages targeted at the .NET framework.
    It looks at the equivalent concepts, keywords, types, operators etc. A very valuable resource when you’re trying to
    read or write code in a language which isn’t your preferred one.[Author: Jon Skeet]
  • Is there an equivalent of MyClass?

    No, C# doesn’t have an equivalent of VB.NET’s MyClass keyword. If you want to guarantee
    not to call an overridden version of a method, you need to make it non-virtual in the first place.[Author: Jon Skeet]
  • What do I use instead of addressof?

    To create delegate instances in C#, you just specify the delegate type, the method, and (if
    you want to create a delegate targetting a different instance or type from the current one) the target.
    For instance, each of these creates a ThreadStart delegate:

    ThreadStart x1 = new ThreadStart(SomeInstanceMethod);ThreadStart x2 = new ThreadStart(AnotherType.SomeStaticMethod);ThreadStart x3 = new ThreadStart(someVariable.SomeInstanceMethod);

    [Author: Jon Skeet]

  • How do I get the rightmost part of a string, as with the VB Right function?

    Use String.Substring. Assuming that x is a string of length at least
    n, to get the last n characters, you would use x.Substring(x.Length-n).Note that the above assumes that the string is at least n characters long. For a more robust version,
    you might use something like: x.Length < n ? x.Substring(x.Length-n) : x.[Author: Jon Skeet]
  • What are the equivalents of Me and MyBase?

    Me in C# is this, and MyBase in C# is base. To access
    normal members, just use this.memberName or base.memberName. For information
    about chaining constructors together, see my
    article on constructors.[Author: Jon Skeet]
  • What’s the equivalent of Nothing?

    For reference types, the equivalent of VB’s Nothing is C#’s null.
    For value types, it’s the default value – 0, false, etc.[Author: Jon Skeet]
  • How do I tell C# what kind of literal number I want?

    If you need to tell C# that you want it to treat a literal as a particular
    type of number, you may do so by adding a number type suffix at the end of
    the literal you provide. For example:

    1u; // An unsigned int1l; // A signed long1ul; // An unsigned long1f; // A System.Single floating-point number;1d; // A System.Double floating-point number
    1m; // a System.Decimal floating-point number

    This is somewhat important because sometimes you must match a literal to the
    signature of something or specify the value to ‘defeat’ an implicit cast
    behavior you don’t like. For example, Hashtable names = new Hashtable(100, 0.1);
    won’t compile because the constructor takes parameters (int, float) and the above is
    (int, double). The line should read Hashtable names = new Hashtable(100, 0.1f);

    A full listing of the suffixes is in the Grammar portion of the C# specification
    (appendix A in the ECMA specification, appendix C in the MS specification). The suffixes are also detailed in the
    Literals section of the specification (9.4.4 of the ECMA specification, 2.4.4 of the MS specification).

    [Author: Jon Skeet]


C# Frequently Asked Questions

The C# team posts answers to common questions

  • Why does my switch statement works differently?

    C# does not support an explicit fall through for case blocks (unless the block is empty)
    For an explanation of why, see Why is the C# switch statement designed to not allow fall through, but still require a break? on MSDN
    The following code is not legal and will not compile in C#:

    switch (x)
    case 0:
    Console.WriteLine(x) // do something
    case 1:
    Console.WriteLine(x) // do something in common with 0
    Console.WriteLine(x) // do something in common with 0, 1 and everything else
    } In order to achieve the same effect in C# the code must be modified as shown below (notice how the control flows are very explicit): class Test {
    static void Main() {
    int x = 3; switch (x) {
    case 0:
    // do something goto case 1;
    case 1:
    // do something in common with 0 goto default;
    // do something in common with 0, 1, and anything else break;

  • Why does C#’s iterators feature spit out a class definition instead of a struct definition?

    Q: Why does C#’s iterators feature spit out a class definition instead of a struct definition?
    The iterators feature in C# generates classes that implement the enumerators required. This is detailed in the C# Specification. Why doesn’t it use structs, which would be more efficient.
    There are two reasons.
    (1) Naming. We generate classes that implement the enumerator interfaces and then use only the interface types in the public protocol. That way the names of the generated classes are purely an implementation detail. This is highly desirable from a versioning perspective. With a struct-based implementation, to get any of the efficiencies associated with structs we would have to use their types in the public protocol (using interfaces the structs would just get boxed). That in turns means we’d have to invent a name mangling scheme for the structs. In particular, iterators returning IEnumerable<T> would be complicated because a type could have multiple such members that differ only in their parameter list, meaning that the parameter list would have to be part of the mangled name.
    (2) Structs don’t work in recursive cases. For example, a TreeNode type could implement an iterator that recursively iterates first the left and then the right subtrees by foreach-ing contained members that are also of type TreeNode. With a struct-based implementation this would translate into an enumerator struct that contains a field of its own type–which isn’t possible. (Think of it this way: A foreach statement obtains an enumerator and stores that in a local variable. In iterators, local variables are transformed into fields in the enumerator. A recursive iterator would therefore create a struct with a member of its own type.) You could argue that we can detect whether or not iterators are recursive and adjust our code generation scheme accordingly. However, you then end up with a versioning problem when a previously non-recursive iterator changes its (supposedly private) implementation to become recursive.
    Anders (via Eric)
  • How can I run another application or batch file from my Visual C# .NET code?

    Posted by: Duncan Mackenzie, MSDN
    This post applies to Visual C# .NET 2002/2003
    Suppose you want to run a command line application, open up another Windows program, or even bring up the default web browser or email program… how can you do this from your C# code?
    The answer for all of these examples is the same, you can use the classes and methods in System.Diagnostics.Process to accomplish these tasks and more.
    Example 1. Running a command line application, without concern for the results:

    private void simpleRun_Click(object sender, System.EventArgs e){

    Example 2. Retrieving the results and waiting until the process stops (running the process synchronously):

    private void runSyncAndGetResults_Click(object sender, System.EventArgs e){
     System.Diagnostics.ProcessStartInfo psi =
       new System.Diagnostics.ProcessStartInfo(@"C:\listfiles.bat");
     psi.RedirectStandardOutput = true;
     psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
     psi.UseShellExecute = false;
     System.Diagnostics.Process listFiles;
     listFiles = System.Diagnostics.Process.Start(psi);
     System.IO.StreamReader myOutput = listFiles.StandardOutput;
     if (listFiles.HasExited)
      string output = myOutput.ReadToEnd();
      this.processResults.Text = output;

    Example 3. Displaying a URL using the default browser on the user’s machine:

    private void launchURL_Click(object sender, System.EventArgs e){
     string targetURL = @http://www.duncanmackenzie.net;

    In my opinion, you are much better off following the third example for URLs, as opposed to executing IE with the URL as an argument. The code shown for Example 3 will launch the user’s default browser, which may or may not be IE; you are more likely to provide the user with the experience they want and you will be taking advantage of the browser that is most likely to have up-to-date connection information.
    C# code download available from http://www.duncanmackenzie.net/Samples/default.aspx
    By the way, this post is a simple port of an earlier VB FAQ post… just in case you thought you had seen it already in your feeds…

  • How do I cast a string to an int, float, double, etc?

    You can use the Convert class or the Parse method of the built-in type you are casting to. i.e.

        string myStr = "123";
        int myParsedInt = Int32.Parse(myStr);
        int myConvertedInt = Convert.ToInt32(myStr);

    This example uses the int type, but you can also use the same techniques for any of the other integral or floating point types.
    [Author: Joe Mayo]

  • How are return values from a delegate handled?

    Q: How are multiple return values from a delegate handled?
    In C#, it’s possible to write a delegate such as:
    delegate double GetResult(params double p);
    If there is more than one method on this delegate, there are multiple return values.
    A: In this situation, the return value is the value that is returned from the last delegate.
    If you want more control on this, you can call GetInvocationList() on the delegate, which will allow you to call each method individually, and process the double values appropriately.
    [Author: Eric Gunnerson]
  • Why don’t nullable relational operators return bool? instead of bool?

    Q: Why don’t nullable relational operators return “bool?” instead of “bool“?
    Nullable types are a new feature of C# 2.0.
    When dealing with nullable types, if you write the following:
    int? i = 15;
    int? j = 16;
    the type of
    i == j
    is a normal bool, rather than a bool? (ie nullable bool). Why?
    A: In our initial designs, we spent a fair amount of time discussing what the behavior should be here, and how we should cross over from the three-valued nullable world to the two-valued “normal C#“ world.
    Consider the following method:
    void Process(int? p)
    if (p == null)
    // do some processing…
    This seems like a very natural thing for a C# user to want to write. But if equality is three-valued, comparing anything to null always returns a null value (ie null isn’t equal to anything), and therefore such a comparison can never succeed. Instead, the user would have to write:
    if (!p.HasValue)
    or something similar. We decided that the value of having a model that was consistent with the way users were used to dealing with reference null was pretty high, and therefore decided to make the relational operators return bool.
  • Why can’t I use the same variable as an inner loop does?

    Q: Why can’t I do the following:
    namespace Bug


    class Class1



    static void Main(string[] args)


    for(int i=0; i<100; i++)



    int i = 0;




    the compiler gives me an error on the “int i = 0;” part of the code.
    A: This is correct behavior, and is covered in section 3.7 of the language spec. It says, “The scope of a local variable declared in a local-variable-declaration (8.5.1) is the block in the which the declaration occurs”.
    The scope of i is therefore the entire Main() function, and that means that the use in the for loop is a re=use, and therefore is not allowed.
    This behavior is inteded to make incorrect re-use of variable names (such as in a cut and paste) less likely.
    [Author: Eric Gunnerson]

  • How do I write a method that accepts a variable number of parameters?

    Q: How do I write a method that accepts a variable number of parameters?

    A: Languages like C and C++ have always offered some means for using and creating functions capable to accept a variable number of parameters. The most widely known example of a function which takes a variable number of parameters is printf():

    int printf(char *format, …); // the ellipsis means variable number of params

    Using this function is pretty easy:

    printf(Hello, world\n);

    printf(The sum of %d and %d is %d\n, a, b, a+b);

    However, the creation of such functions in these languages relays on a set of predefined macros and is not particularly elegant or intuitive.

    C# offers an elegant solution to this problem through parameter arrays. A parameter array is a single-dimensional array included as the last parameter in the parameter list of a method:

    public string Concat(string separator, params string[] strings)


    string result = “”;

    for (int i = 0; i < strings.Length; i++)


    if (i > 0)

    result += separator;

    result += strings[i];


    return result;


    Such a function can be called in two different ways:

    a) Passing the function an array instance argument:

    string[] names = { “Anders”, “Eric”, “Scott”, “Duncan” };

    MessageBox.Show(Concat(“+”, names) + ” = great team”);

    b) Using zero or more type-compatible arguments for the parameter array:

    MessageBox.Show(Concat(“+”, “Anders”, “Eric”, “Scott”, “Duncan”) +

    ” = great team”);

    In this case, the invocation will create an array from the supplied arguments and use it as the actual argument.

    Thanks to the unified .NET type system, object[] can be used as “common denominator” for arguments of different types:

    public int SumTheIntegers(params object[] list)


    // sum all the integers included in list

    int sum = 0;

    foreach (object o in list)

    if (o.GetType() == typeof(int))

    sum += (int) o;

    return sum;


    [Author: Octavio “Dave” Hernandez]

  • Why doesn’t C# support static method variables?

    Q: In C++, it’s possible to write a static method variable, and have a variable that can only be accessed from inside the method. C# doesn’t provide this feature. Why?
    A: There are two reasons C# doesn’t have this feature.
    First, it is possible to get nearly the same effect by having a class-level static, and adding method statics would require increased complexity.
    Second, method level statics are somewhat notorious for causing problems when code is called repeatedly or from multiple threads, and since the definitions are in the methods, it’s harder to find the definitions.
    [Author: Eric Gunnerson]
  • Why must attribute properties be read/write in C#?

    Q: Why must attribute properties be read/write in C#?
    In the C# language, when you define an attribute class, you can define both constructor arguments and properties. For example:

    class MyAttribute: Attribute
         string name;
         int number;
         public MyAttribute(string name) { this.name = name;}
         public int Number
             get {return number;}
             set {number = value; }
         public string Name
             get {return name;}
     [My("Fred", Number=5)]
     class Fred

    When you do this, C# requires that properties (such as Number in this example) be read/write properties, though languages such as VB.NET only require them to be readable.
    A: Using an attribute in C# is logically equivalent to calling the constructor of the attribute class, and then executing the “property = value” part for each named property. Requiring a writeable property is consistent with this view.
    Author: Eric Gunnerson

  • Why do I get the error “Object reference not set to an instance of an object”?

    The code is trying to access a member of a reference type variable that is set to null.
    Given the following class, let’s examine some code that could be in the Main method:

    using System;class Foo
      static void Main()
       // foo has not been instantiated
       Foo foo = null;
    // implementation to be discussed...
    public int BarProperty
       get { return 0; }
    public string BarMethod()
       return null;

    Looking at Main, notice that foo is set to null. Your situation will not be this explicit because the variable you are trying to use could be a class field, parameter, or local variable that was once instantiated but was subseqently set to null. Given that foo is null, the following code will throw a NullReferenceException:

        // foo is null, and you can't call
        // BarProperty on null.
        int resultBad = foo.BarProperty;
       catch (NullReferenceException nre)
         "\nCan't read BarProperty, foo is null.\n" +

    Since foo is null, you can not use its members. This was a property, but the following code demonstrates calling a method:

        // foo is null, and you can't call
        // BarMethod on null.
       catch (NullReferenceException nre)
         "\nCan't call BarMethod(), foo is null.\n" +

    The code above throws a NullReferenceException because foo is still null. It doesn’t matter that the first call was a property and the second is a method – they are both members of the type.
    Now, to fix this problem, you must ensure that foo is instantiated before it is used. The following code instantiates foo and the previous problems are solved:

      // now we have an instance
       foo = new Foo();  // works fine
       int resultGood = foo.BarProperty;

    Since foo now refers to a valid instance, the code can call any of its members. This was easier than many null reference problems. Sometimes you have multiple levels of indirection, leaving you with a scenario you didn’t expect. Assuming that foo now references an object, there is still a problem with the following code:

        // still breaks because BarMethod() returned
        // null and you can't call Trim() on null.
       catch (NullReferenceException nre)
         "\nCan't call Trim(), BarMethod() returns null.\n" +

    The problem occurs in the code above because BarMethod returned null, which means that the code is trying to call the Trim method on a string reference that is set to null.
    The proper way to fix this problem is to debug BarMethod to find out why it returned null. That assumes BarMethod is not supposed to return null. If, in your application, it made sense for BarMethod to sometimes return null, then you would have to check the return value of BarMethod before you called any members of the return value.
    [Author: Joe Mayo]

  • Why did I receive the error: “The type or namespace ‘<namespace name>’ does not exist in the class or namespace ‘<parent namespace>’ (are you missing an assembly reference?)”

    You need to add a reference in your project to an assembly where that namespace is defined.
    If you are using VS.NET:
    1. Right click on the References folder on your project.
    2. Select Add Reference.
    3. Select the .NET tab (or select the Browse button if it is not a .NET Framework assembly).
    4. Double-click the assembly containing the namespace in the error message.
    5. Press the OK button.
    If you are using the command line, use the /r: or /reference: option. For Example:
    csc.exe /reference:System.Drawing.dll MyFontDisplayApp.cs
    When you recompile, this error will no longer appear.
    You can find the assembly, where a namespace is defined, in the documentation. Identify one of the types in the namespace that you want to use. Every type in the .NET Framework has an “About” page that provides an overview, basic information about the type, and example code if you’re lucky. At the bottom of the Overview, for all types, there is a “Requirements” section. This has a Namespace member that tells what namespace the type belongs to. It also tells what assembly type belongs to, which is the assembly you need to reference in your application. For example, if I had an application that was using Font types, I would look up Font in the .NET Framework documentation, using the Index tab, and observe that the Font type is in the System.Drawing namespace and its assembly is System.Drawing.dll.
    Another question related to this is “If I’ve already declared a using statement, why do I have to add the reference to the project?”
    The reason derives from the fact that the using statement and assembly references have two different purposes. Recall that the purpose of namespaces is to disambiguate type references and provide logical organization of types. When specifying a namespace in a using statement, you are telling C# that you want to use the types in that namespace in an unqualified manner. The key point is that namespaces are “logical” entities that could exist in one or more assemblies. On the other hand, assemblies are “physical” entities that contain multiple types. Assemblies are many things, but for the purposes of this discussion, an assembly is the unit of deployment in .NET. So, the reason you need a reference to the assembly that the type is located in is so that C# can find the physical location of that type, which is not possible with the logical namespace provided by a using statement.
    [Author: Joe Mayo]
  • How can I subscribe to events exposed by a remoted object?

    Delegates require information about the type that the method is associated with in order to make a call. In a single app-domain, this isn’t a problem, because the server (the object firing the events) has access to the type information for the client (which has the event handlers) by way of the delegate.
    However, during remoting, the server most likely does not have any information about the client. If you want events from the server to fire in the client app domain, then the client must derive from MarshalByRefObject. This is required so that the server will call back into the client, as opposed to a copy of the client object that is passed to the server.
    A simple way to do this is to place a copy of the client assembly in the same directory where the server directory is. While this will work, it is not an elegant solution, as it exposes the client type unecessarily.
    A more elegant solution (albiet more complex), is to have a single assembly that is referenced by both the client and the server. This assembly will have a shim class which will expose methods that share the signature of the events that you want to shim. The assembly will also provide an interface with methods that share the signature of the events as well. The shim will then take a reference to the interface, and the methods will aggregate the call to the interface that was passed in (I recommend the constructor as the place to pass the interface implementation).
    Finally, the client object will implement the interface. When subscribing to the events that the server exposes, attach the delegates to the methods on the shim, which will be passed your client object’s implementation.
    It is also important to note that in order for this to work, the TypeFilterLevel property on the sink provider for the server needs to be set to TypeFilterLevel.Full.
  • Why does my Windows Form project not use visual styles in XP even when I call Application.EnableVisualStyles?

    If you set a property on a Windows Forms control which forces the creation of the control (e.g. the SelectedIndex property on the ComboBox class), the control (and perhaps the rest of the form) will not render with visual styles enabled.
    The resolution is to place the code that sets these properties in an event handler for the Load event on the form/control.
  • Why aren’t reference types polymorphic?

    Q: Why aren’t reference types polymorphic?
    A: Consider the following code:

    using System;
    class Dog {
       public string Name;
    class Test
       public static void Swap(ref object a, ref object b) {
          object temp;
          temp = a;
          a = b;
          b = temp;
    public static void Main() {
           Dog d1 = new Dog();
           d1.Name = "fido";
           Dog d2 = new Dog();
           d2.Name = "rex";
           Swap(ref d1, ref d2);

    The compiler will report an error on the call to the Swap() function. Why? Consider if the swap function was like this:

       public static void Swap(ref object a, ref object b) {
    a = 5;
    b = “Hello“;

    If the compiler allowed this code, it would mean assigning a boxed int to a Dog object, which is clearly not type safe.
    [Author: Eric Gunnerson]