Sunday, December 23, 2012

Why use a question marks in parameter list - C#.NET

See the below code sample.

private void NullTest(int? a, bool? b, string c)
  if (b.HasValue)
  Response.Write(b.ToString() + "<br/>");
  Response.Write(c.ToString() + "<br/>");

You'll see there are question marks passed in the parameter list. It means that the field is nullable, simply means you can pass null values as the parameter.

NullTest(1, true, "test");

Out put:

You are allowed to pass the parameters as below as well.
NullTest(null, null, "test");

Out put:

Note that parameter "c" is not nullable. If you try to make the parameter "c" nullable, you'll get the following error.

"The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'"

Reason why you are getting the error is System.String is a reference type and already "nullable".
Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

You can read about value types and reference types here.

No comments:
Write comments
Recommended Posts × +