Frequently Asked Questions: The Following Is A List of Common Questions About C# With Answers From The C# Team
Frequently Asked Questions: The Following Is A List of Common Questions About C# With Answers From The C# Team
The following is a list of common questions about C# with answers from the C# Team.
• Why do I get a syntax error when trying to declare a variable called checked?
• What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname()
does not compile)?
• Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
• I have several source files, each of which has a Main() method. How do I specify which of those Main()'s is
supposed to be used?
• Does Console.WriteLine() stop printing when it reaches a NULL character within a string?
• Why does my Windows application pop up a console window every time I run it?
• Why is the compiler referencing things that I'm not telling it to reference?
• I'm trying to implement an interface defined in COM+ runtime. "public Object* GetObject() { ... }" doesn't
seem to work. What can I do?
• Why do I get a CS0117 error when attempting to use the 'Item' property?
• I was trying to use an "out int" parameter in one of my functions. How should I declare the variable that I
am passing to it?
• Is there an equivalent to C++'s reference parameters in C# (that is, void foo(int &i))?
• Why do I get a "CS5001: does not have an entry point defined" error when compiling?
• How do you implement thread synchronization (Object.Wait, Notify, and CriticalSection) in C#?
1
• What's the syntax for a static initializer for my class?
• Is there a way of specifying which block or loop to break out of when working with nested loops?
• How do you specify a custom attribute for the entire assembly (rather than for a class)?
• When using multiple compilation units (C# source files), how is the executable's name determined?
• Can I define a type that is an alias of another type (like typedef in C++)?
• From a versioning perspective, what are the drawbacks of extending an interface as opposed to extending a
class?
• Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?
• If I return out of a try/finally in C#, does the code in the finally-clause run?
• What optimizations does the C# compiler perform when you use the /optimize+ compiler option?
• How can I create a process that is running a supplied native executable (e.g., cmd.exe)?
• I've added a using to my C# source file, but it's still telling me that I have undefined types. What am I
doing wrong?
2
• How do I call the base class's implementation of an overridden method?
A: All methods marked with the DllImport attribute must be marked as public static extern.
A: C# does not support an explicit fall through for case blocks. The following code is not legal and will not
compile in C#:
switch(x)
case 0:
// do something
case 1:
default:
break;
}
To achieve the same effect in C#, the code must be
modified as shown below (notice how the control flows are explicit):
3
class Test
int x = 3;
switch(x)
case 0:
// do something
goto case 1;
case 1:
goto default;
default:
break;
4
Q: What is the difference between const and static read-only?
A: The difference is that static read-only can be modified by the containing class, but const can never be
To expand on the static read-only case a bit, the containing class can only modify it:
5
Q: How do I do implement a trace and assert?
class Debug
[conditional("TRACE")]
Console.WriteLine(s);
class MyClass
Debug.Trace("hello");
preprocessor symbol TRACE is defined at the call site. You can define preprocessor symbols on the command
line by using the /D switch. The restriction on conditional methods is that they must have void return type.
6
Q: Why do I get a syntax error when trying to declare a variable called checked?
Q: What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname()
does not compile)?
class B
B(int i)
{ }
class C : B
{ }
{ }
expr is type
7
Q: How do I use enum's in C#?
A: Here's an example:
namespace Foo
enum Colors
BLUE,
GREEN
class Bar
Colors color;
8
Q: Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
A: If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a
constructor.
So if you are trying to declare a method that returns nothing, use void.
Q: I have several source files, each of which has a Main() method. How do I specify which of those Main()'s is
supposed to be used?
A: The entry point of your program must be static, named Main, have arguments of either none or string[],
The C# compiler now allows you to have multiple Main() methods in your application, but requires you to
specify the fully qualified class name that has the Main() method you want to use. You specify the class by
using the /main compiler option (for example, csc /main:MyClass *.cs)
Note that the way to set it in the Visual Studio .NET IDE is through -> Project Properties, Common properties,
General. Then set the Startup object to the name of the class that contains the main method you want to use.
Q: Does Console.WriteLine() stop printing when it reaches a NULL character within a string?
A: Strings are not null terminated in the runtime, so embedded nulls are allowed. Console.WriteLine() and all
9
Q: Is it possible to use multicast delegates in C#? What's the syntax?
A: All delegates in C# are multicast; therefore, there is no 'multicast' keyword as there was in Visual J++.
A: C# requires only a single parameter for delegates: the method address. Unlike other languages, where the
programmer must specify an object reference and the method to invoke, C# can infer both pieces of
information by just specifying the method's name. For example, let's use System.Threading.ThreadStart:
invoke static class methods and instance methods with the exact same syntax!
Q: Why does my Windows application pop up a console window every time I run it?
A: Make sure that the target type set in the project properties setting is set to Windows Application, and not
Console Application. If you're using the command line, compile with /target:winexe & not /target:exe.
If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be doing it for you,
you can force finalizers to be run by setting all the references to the object to null and then calling
System.GC.RunFinalizers().
Keep in mind that what some of the predefined C macros (for example, __LINE__ and __FILE__) give you can
also be found in .NET classes like System.Diagnostics (for example, StackTrace and StackFrame), but they'll
10
Q: Why is the compiler referencing things that I'm not telling it to reference?
A: The C# compiler automatically references all the assemblies listed in the 'csc.rsp' file. You can disable the
usage of the csc.rsp file by using the /noconfig compiler option on your command line.
Note that the Visual Studio .NET IDE never uses the response file.
using System.Runtime.InteropServices;
class C
[DllImport("user32.dll")]
This example shows the minimum requirements for declaring a C# method that is implemented in a native
DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport
attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name
of MessageBoxA.
For more information, look at the Platform Invoke tutorial in the documentation.
11
Q: I'm trying to implement an interface defined in COM+ runtime. "public Object* GetObject() { ... }" doesn't
seem to work. What can I do?
A: In managed C++, the "Object* GetObject()" (pointer to Object) syntax is required. But in C#, it should
A: No. However, there are plans for C# to support a type of template known as a generic. These generic types
have similar syntax but are instantiated at run time as opposed to compile time. You can read more about
them here.
12
Q: Why do I get a CS0117 error when attempting to use the 'Item' property?
A: Properties are supported in C#, but the "Item" property is special on classes—it is actually the default
indexed property. In C#, the way to access these is to simply leave the "Item" specifier off.
using System;
using System.Collections;
class Test
}
Notice the way that
13
Q: I was trying to use an "out int" parameter in one of my functions. How should I declare the variable that I
am passing to it?
A: You should declare the variable as an int, but when you pass it in you must specify it as 'out', like the
following:
int i;
foo(out i);
14
Q: Is there an equivalent to C++'s reference parameters in C# (that is, void foo(int &i))?
class Test
i = 1;
int a = 0;
foo(ref a);
if (a == 1)
Console.WriteLine("It worked");
}
Note that you're required to restate the ref
in a method invocation.
15
Q: How do I declare inout arguments in C#?
...
}
When calling the method,
String s1;
String s2;
s1 = "Hello";
Console.WriteLine(s1);
Console.WriteLine(s2);
Notice that you need to specify ref when declaring the function
16
Q: How do destructors and garbage collection work in C#?
A: C# has finalizers (similar to destructors except that the runtime doesn't guarantee they'll be called), and
class C
~C()
// your code
}
Currently, they override object.Finalize(), which is called
Q: Why do I get a "CS5001: does not have an entry point defined" error when compiling?
A: The most common problem is that you used a lowercase 'm' when defining the Main method. The correct
class test
17
Q: How do I port "synchronized" functions from Visual J++ to C#?
// function body
}
Ported C# code:
class C
lock(this)
// function body
18
Q: How do you implement thread synchronization (Object.Wait, Notify, and CriticalSection) in C#?
A: You want the lock statement, which is the same as Monitor Enter/Exit:
lock(obj)
// code
}
translates to:
try
CriticalSection.Enter(obj);
// code
finally
CriticalSection.Exit(obj);
19
Q: What's the syntax for a static initializer for my class?
class MyClass
static MyClass()
A: No. The access modifier on a property applies to both its get and set accessors. What you need to do if you
want them to be different is make the property read-only (by only providing a get accessor) and create a
20
Q: Does C# support properties of array types?
using System;
class Class1
class MainClass
c.MyProperty = arr;
Console.WriteLine(c.MyProperty[0]); // "apple"
return 0;
21
22