3

I would like to have something like tkis "int?" but for string. You know if I will not give data to parameter I will not got error. I need some idea to this problem.

Example(4);

public void Example(int, string?){} 

For all of you I give points. Thanks for help. Topic [closed] :)

1
  • 5
    String are nullable by default that's why there is no need for string?. Commented Oct 25, 2012 at 9:53

5 Answers 5

11

This isn't available as string is already a reference type, so is already nullable. The ? suffix is syntactic sugar for Nullable<T>, so int? is equivalent to Nullable<int>... and Nullable<T> has a constraint of where T : struct, i.e. T has to be a non-nullable value type... which excludes string.

In other words, you can just write

public void Example(int x, string y)
{
    if (y == null)
    {
        ...
    }
}

Note that this is different from making it an optional parameter. Passing in a null value is still passing in a value. If you want to make it an optional parameter you can do that too:

public void Example(int x, string y = "Fred")

...

Example(10); // Equivalent to Example(10, "Fred");
Sign up to request clarification or add additional context in comments.

1 Comment

Jon for your example you can also write if (x == null) but with a warning :)
4

System.String is a reference type, so you can assign to a String variable null without declaring the variable nullable.

Comments

4

string type take null by default and you do not need to make it nullable as it is already reference type. You can use it this way.

public void Example(int i, string s)
{

} 

Call it with null will be

Example(null, null);

Comments

4

In C# 4.0 you can use optional parameters by writing

public void Example (int a, string b = null) {}

Otherwise, you can overload the method

public void Example (int a) {}
public void Example (int a, string b) {}

Comments

2

Do you need to give the string argument a default value?

e.g.

Example(4);

public void Example(int x, string y = null)
{
    // etc
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.