简体   繁体   中英

Inline reference types to methods?

I am working with an API that contains a method with a reference type. I don't always need to pass information into the method. Is there some way to pass a default or null value inline?

What I'm currently doing:

MyObject obj = null;
MyMethod(ref obj);

What I'd like to do is something like:

MyMethod(ref null);

I understand why this doesn't work, but it gets the point across.

you can't modify null . parameters declared as ref (or out ) must be named variables. null is a value.

that is not a reference type - that is a pass by reference parameter. That means MyMethod can modify the reference to obj .

That API is likely expecting to give the caller something. Carefully read the documentation to see what it expects.

In my best guess, the caller should always provide it a value when it is ref . That way the method can use it as needed. Otherwise, the method should have declared it as out .

null is a value... Ref keyword means that you should pass reference to some instance (which is typically just a variable) and not value. That's why when method expects reference to a variable - it doesn't accept null . For example:

void A(ref string str)  // expects reference not value
{
} 

void A(string str)  // expects value not reference
{
} 

Create a second method without the parameter:

private void MyMethod()
{
    MyObject notNeeded = null;
    MyMethod(ref notNeeded);
}

Nevertheless, as the others already mentioned there seems to be something wrong in your design, if this method doesn't need the given reference all the time. Maybe you should think about what your method is doing and maybe split it up into multiple methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM