Reputation: 1005
All over in our code we type check things, and then immediately need to cast them. Something like this:
if((foo is SomeClass) && (foo as SomeClass).Bar != null) {
SomeClass fooClass = foo as SomeClass;
DoSomething(fooClass.Bar);
...
}
What I wish is that there was some way that, after an explicit type check, references to foo
could implicitly be converted to the class:
if (foo is SomeClass && foo.Bar != null) {
DoSomething(foo.Bar);
}
It passed (foo is SomeClass)
so we know that foo
is a SomeClass
. The as
cast seems superfluous. If you're inside a statement where you have passed (foo is SomeClass)
then it seems like you shouldn't have to then explicitly convert foo
to SomeClass
Before anyone says anything about coding practices... I know. Ideally in most places in our application we make good use of generics, abstract classes, interfaces, and all other methods to interact with objects in a reasonable manner. But sometimes you get an object
and need to check it, especially out of things like events. I don't have a real problem with doing is
/as
all over, I was just curious if there was some syntactical magic I could employ that was a bit cleaner. This is an experiment in syntax optimization, not practicality.
As a test, I played with an extension method called I called IsAs
:
public static bool IsAs<T>(this object check, out T result) {
if (check is T) {
result = (T)check;
return true;
}
result = default(T);
return false;
}
This returns a bool, fulfilling the is
portion, and uses a reference input to populate the cast value for the as
. But in practice, the syntax is not much cleaner:
SomeClass fooClass;
if(foo.IsAs<SomeClass>(out fooClass) && fooClass.Bar != null) {
DoSomething(fooClass)
...
}
Upvotes: 2
Views: 79
Reputation: 7553
Using an is
type pattern expression, you can assign the resulting cast to a variable:
if (foo is SomeClass fooSomeClass && fooSomeClass.Bar != null)
{
DoSomething(fooSomeClass.Bar);
}
Upvotes: 10