0% found this document useful (0 votes)
78 views

Frequently Asked Questions: The Following Is A List of Common Questions About C# With Answers From The C# Team

This document contains a list of frequently asked questions about C# and their answers. Some common questions addressed include how to use DllImport, differences between const and static readonly, how to implement tracing and assertions, how to make a DLL in C#, why a variable cannot be called "checked", proper syntax for calling constructors from other constructors, differences between a struct and class, how to break out of nested loops, and how exception handling works in C#.

Uploaded by

api-3748960
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Frequently Asked Questions: The Following Is A List of Common Questions About C# With Answers From The C# Team

This document contains a list of frequently asked questions about C# and their answers. Some common questions addressed include how to use DllImport, differences between const and static readonly, how to implement tracing and assertions, how to make a DLL in C#, why a variable cannot be called "checked", proper syntax for calling constructors from other constructors, differences between a struct and class, how to break out of nested loops, and how exception handling works in C#.

Uploaded by

api-3748960
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 22

Frequently Asked Questions

The following is a list of common questions about C# with answers from the C# Team.

• Why does DllImport not work for me?

• My switch statement works differently! Why?

• What is the difference between const and static read-only?

• How do I do implement a trace and assert?

• How do I make a DLL in C#?

• 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)?

• Is there an equivalent to the instanceof operator in Visual J++?

• How do I use enum's in C#?

• 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?

• Is it possible to use multicast delegates in C#? What's the syntax?

• How do I create a Delegate/MulticastDelegate?

• Why does my Windows application pop up a console window every time I run it?

• Is there a way to force garbage collection?

• Does C# support C type macros?

• Why is the compiler referencing things that I'm not telling it to reference?

• How do you directly call a native function exported from a DLL?

• I'm trying to implement an interface defined in COM+ runtime. "public Object* GetObject() { ... }" doesn't
seem to work. What can I do?

• Does C# support templates?

• 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))?

• How do I declare inout arguments in C#?

• How do destructors and garbage collection work in C#?

• Why do I get a "CS5001: does not have an entry point defined" error when compiling?

• How do I port "synchronized" functions from Visual J++ to C#?

• 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 it possible to have different access modifiers on the get/set methods of a property?

• How do I create a multi-language, single-file assembly?

• Does C# support properties of array types?

• How do I create a multi-language, multi-file assembly?

• How do I simulate optional parameters to COM calls?

• Is there an equivalent to C++'s default values for function arguments?

• Is there a way of specifying which block or loop to break out of when working with nested loops?

• How do I get deterministic finalization in C#?

• Does C# support variable arguments (vararg's) on methods?

• How do I convert a string to an int in C#?

• Is there an equivalent of exit() for quitting a C# .NET application?

• How do you specify a custom attribute for the entire assembly (rather than for a class)?

• How do I register my code for use by classic COM clients?

• When using multiple compilation units (C# source files), how is the executable's name determined?

• How does one compare strings in C#?

• Can I define a type that is an alias of another type (like typedef in C++)?

• What is the difference between a struct and a class in C#?

• How can I get the ASCII code for a character in C#?

• From a versioning perspective, what are the drawbacks of extending an interface as opposed to extending a
class?

• Is it possible to inline assembly or IL in C# code?

• 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?

• Does C# support try-catch-finally blocks?

• Is it possible to have a static indexer in C#?

• What optimizations does the C# compiler perform when you use the /optimize+ compiler option?

• How can I access the registry from C# code?

• Does C# support #define for defining global constants?

• How can I create a process that is running a supplied native executable (e.g., cmd.exe)?

• How do you mark a method obsolete?

• 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?

• Is there any sample C# code for simple threading?

2
• How do I call the base class's implementation of an overridden method?

• Is there regular expression (regex) support available to C# developers?

• Why do I get a security exception when I try to run my C# app?

• How can I get around scope problems in a try/catch?

• What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?

• Does C# support parameterized properties?

Q: Why does DllImport not work for me?

A: All methods marked with the DllImport attribute must be marked as public static extern.

Q: My switch statement works differently! Why?

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:

// do something in common with 0

default:

// do something in common with

//0, 1 and everything else

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

public 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;

default:

// do something in common with 0, 1, and anything else

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

modified and must be initialized to a compile time constant.

To expand on the static read-only case a bit, the containing class can only modify it:

-- in the variable declaration (through a variable initializer).

-- in the static constructor (instance constructors if it's not static).

5
Q: How do I do implement a trace and assert?

A: Use a conditional attribute on the method, as shown below:

class Debug

[conditional("TRACE")]

public void Trace(string s)

Console.WriteLine(s);

class MyClass

public static void Main()

Debug.Trace("hello");

In this example, the call to Debug.Trace() is made only if the

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.

Q: How do I make a DLL in C#?

A: You need to use the /target:library compiler option.

6
Q: Why do I get a syntax error when trying to declare a variable called checked?

A: The word checked is a keyword in C#.

Q: What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname()
does not compile)?

A: The syntax for calling another constructor is as follows:

class B

B(int i)

{ }

class C : B

C() : base(5) // call base constructor B(5)

{ }

C(int i) : this() // call C()

{ }

public static void Main() {}

Q: Is there an equivalent to the instanceof operator in Visual J++?

A: C# has the is operator:

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;

Bar() { color = Colors.GREEN;}

public static void Main() {}

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.

The following is an example:

// This results in a CS1006 error

public static staticMethod (mainStatic obj)

// This will work as wanted

public static void staticMethod (mainStatic obj)

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[],

and return either int or void.

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

similar methods continue until the end of the string.

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++.

Q: How do I create a Delegate/MulticastDelegate?

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:

Foo MyFoo = new Foo();

ThreadStart del = new ThreadStart(MyFoo.Baz);


This means that delegates can

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.

Q: Is there a way to force garbage collection?

A: Yes. Set all references to null and then call System.GC.Collect().

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().

Q: Does C# support C type macros?

A: No. C# does not have macros.

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

only work on debug builds.

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.

Q: How do you directly call a native function exported from a DLL?

A: Here's a quick example of the DllImport attribute in action:

using System.Runtime.InteropServices;

class C

[DllImport("user32.dll")]

public static extern int MessageBoxA(int h, string m, string c, int


type);

public static int Main()

return MessageBoxA(0, "Hello World!", "Caption", 0);

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

work by just using "public Object GetObject() { ... }" instead.

Q: Does C# support templates?

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.

Here's a simple program:

using System;

using System.Collections;

class Test

public static void Main()

ArrayList al = new ArrayList();

al.Add( new Test() );

al.Add( new Test() );

Console.WriteLine("First Element is {0}", al[0]);

}
Notice the way that

you don't use ".Item[0]" in the WriteLine.

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);

where foo is declared as follows:

[return-type] foo(out int o) { }

14
Q: Is there an equivalent to C++'s reference parameters in C# (that is, void foo(int &i))?

A: We call them ref parameters:

class Test

public void foo(ref int i)

i = 1;

public void bar()

int a = 0;

foo(ref a);

if (a == 1)

Console.WriteLine("It worked");

public static void Main() {}

}
Note that you're required to restate the ref

in a method invocation.

15
Q: How do I declare inout arguments in C#?

A: The equivalent of inout in C# is ref. , as shown in the following example:

public void MyMethod (ref String str1, out String str2)

...

}
When calling the method,

it would be called like this:

String s1;

String s2;

s1 = "Hello";

MyMethod(ref s1, out s2);

Console.WriteLine(s1);

Console.WriteLine(s2);
Notice that you need to specify ref when declaring the function

and calling it.

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

they are specified as follows:

class C

~C()

// your code

public static void Main() {}

}
Currently, they override object.Finalize(), which is called

during the GC process.

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

way to implement the entry point is as follows:

class test

static void Main(string[] args) {}

17
Q: How do I port "synchronized" functions from Visual J++ to C#?

A: Original Visual J++ code:

public synchronized void Run()

// function body

}
Ported C# code:

class C

public void Run()

lock(this)

// function body

public static void Main() {}

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?

A: The following is a class with a static initializer block:

class MyClass

static MyClass()

// initialize static variables here

public static void Main() {}

Q: Is it possible to have different access modifiers on the get/set methods of a property?

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

private/internal set method that is separate from the property.

Q: How do I create a multilanguage, single-file assembly?

A: This is currently not supported by Visual Studio .NET.

20
Q: Does C# support properties of array types?

A: Yes. Here's a simple example:

using System;

class Class1

private string[] MyField;

public string[] MyProperty

get { return MyField; }

set { MyField = value; }

class MainClass

public static int Main(string[] args)

Class1 c = new Class1();

string[] arr = new string[] {"apple", "banana"};

c.MyProperty = arr;

Console.WriteLine(c.MyProperty[0]); // "apple"

return 0;

21
22

You might also like