See the below code sample.
private void NullTest(int? a, bool? b, string c)
{
if(a.HasValue)
Response.Write(a.ToString()+"<br/>");
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:
1
True
Test
You are allowed to pass the parameters as below as well.
NullTest(null, null, "test");
Out put:
Test
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.
Sunday, December 23, 2012
Why use a question marks in parameter list - C#.NET
Subscribe to:
Post Comments (Atom)
No comments:
Write comments