I do not know what it is called exactly, but for now I will refer to it as 'not null test'. In C# 8 there is a new behavior which allows to test if an object is not null e.g.:
Foo foo = new Foo();
if(foo is { })
{
//foo is not null
}
You can also extract properties from this object:
public class Foo
{
public int Bar { get; set; }
}
Foo foo = new Foo();
if(foo is { Bar: var bar })
{
//Foo is not null and bar contains the value of the property of the foo instance
}
So far so good, but I imagine it to be similar to something like this:
public bool GetBar(Foo foo, out int bar)
{
if(foo is null)
{
return false;
}
bar = foo.Bar;
return true;
}
Which would be used as something like this:
Foo foo = new Foo();
if(GetBar(foo, out var bar))
{
//Foo is not null and bar contains the value of the property of the foo instance
}
Now my actual question: Is there any way I could use the behavior of ref? Which would look something like this:
if(foo is { Bar: ref var bar })
{
//Foo is not null and bar contains the value of the property of the foo instance
}
I would understand if this does not exist since out ref
does not exist either. So is there any way you can do this, or is there anything that would speak against it?