Tom Rider
Tom Rider

Reputation: 2815

Method contains default parameter value

I want to define a function in c# with 2 parameters and they have their default values , like

    public T AccessEntity(string Id = null, string File = null)
    {
        return (from e in ServiceContext.CreateQuery<T>(TableName)
                where e.RowKey == Id || e.File == File
                select e).FirstOrDefault();
    }

Now with this function user can search their record by file or id but if user try to search the record by file then how we can map the first argument to second formal parameter without passing any dummy value as a first argument.

I do not want this : invokingobj.AccessEntity(null, "name of file");

Is this possible ?

Upvotes: 1

Views: 181

Answers (6)

Carsten Sch&#252;tte
Carsten Sch&#252;tte

Reputation: 4558

Yes, try this:

 invokingobj.AccessEntity(File: "name of file");

This language feature is called "named parameters" and is an extension of the well-known "optional parameters".

Upvotes: 0

Jo&#227;o Angelo
Jo&#227;o Angelo

Reputation: 57688

You can invoke the method with named parameters arguments:

invokingobj.AccessEntity(File: "name of file");

More information about the use of named arguments an optional parameters can be found in:

Named and Optional Arguments (C# Programming Guide)

Upvotes: 3

Servy
Servy

Reputation: 203829

One option is to create several different methods. (You could have different overloads if the parameters had a different type, but since they're both string you can't.)

public T AccessEntityById(string Id)
{
    return AccessEntity(Id, null);
}

public T AccessEntityByFile(string file)
{
    return AccessEntity(null, file);
}

Upvotes: 0

millimoose
millimoose

Reputation: 39950

Use named parameters:

invokingObj.AccessEntity(file: "name of file");

Upvotes: 1

marc_s
marc_s

Reputation: 754488

I do not want this : invokingobj.AccessEntity(null, "name of file");

You don't have to - you can do :

invokingobj.AccessEntity(File:"name of file");

You can define which parameter to set when you call a function by using the named parameter feature

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500555

You can use named arguments:

invokingobj.AccessEntity(File: "name of file")

Note that you should rename your parameter to file though, to comply with normal .NET naming conventions ("do use camel casing in parameter names").

As an aside, almost everyone - including MSDN - gets confused about the names of the two defaults here. They are optional parameters (it's the parameter which is decorated with the default value) but named arguments (parameters have always had names - it's arguments that are allowed to specify a name in C# 4).

Upvotes: 5

Related Questions