NoWar
NoWar

Reputation: 37642

Optional C# parameter issue

I have this method

public static void WriteErrorLog(LogEntry logEntry, string method, [Optional, DefaultParameterValue(0)]  int? errorTypeID)

So I expect that I can call the method like

WriteErrorLog(l, "text");

But I get an error of Visual Studio anyway :(

No overload for method 'WriteErrorLog' takes 2 arguments

What I am missing?

Thank you!

Upvotes: 2

Views: 255

Answers (5)

Chris Pfohl
Chris Pfohl

Reputation: 19074

You're problem is that [Optional] is not how you make it optional. Try:

public static void WriteErrorLog(LogEntry logEntry, string method, [Optional, DefaultParameterValue(0)]  int? errorTypeID = null)

Optional parameters were added in C# 4.0 and are a simple alternative to method overloading. Under the hood it gets expanded where you call it to a call including the default value you give it. You can leave the [Optional] attribute. It doesn't hurt at all. In fact, I'm not sure if it does anything at all. If I had to guess it was to make overloads easier to use by marking ones that could be omitted because another overload handled the default for you.

Upvotes: 6

Matt Utley
Matt Utley

Reputation: 16

I don't know why it isn't working for you. I copied the method parameters exactly how you typed them. I use VS2010 and .NET 4.0. I ran the code and it works just fine every time.

You should be using the C-style default parameters anyhow. But this method still works for me. I get a red underline, however, and hovering displays the same error. But when I run the code everything works as it should.

Upvotes: 0

kol
kol

Reputation: 28728

If you use .NET 4 (or newer):

public static void WriteErrorLog(LogEntry logEntry, string method, int? errorTypeID = null)

Note that the "default" value for a nullable type is null. In C, people usually use -1 or 0 as the default value of integers, this is what you can do more cleanly in C# with nullables. AFAIK there is something similar in Haskell, and other languages.

Upvotes: 0

code4life
code4life

Reputation: 15794

You need to state optional parameters this way:

public static void WriteErrorLog(LogEntry logEntry, 
    string method, int? errorTypeID = 0)

This will compile properly.

Upvotes: 3

Hans Z
Hans Z

Reputation: 4744

You're not supposed to be using [Optional, DefaultParameterValue(0)]. Instead, you should use the c-style default parameter syntax:

public static void WriteErrorLog(LogEntry logEntry, string method, int? errorTypeID = 0)

Also, if errorTypeId is a Nullable, then shouldn't you have the default value be null?

public static void WriteErrorLog(LogEntry logEntry, string method, int? errorTypeID = null)

Upvotes: 16

Related Questions