Streamlined way to do C# run-time type identification that avoids a NULL check?
Asked Answered
K

3

2

I find myself using a common run-time type identification pattern, especially when writing code that handles controls of varying types. Here is the pattern:

if (ctrl is ControlTypeEtc)
    (ctrl as ControlTypeEtc).SomeMethod();

I do this to avoid having to do a NULL check in case the as operator returns NULL. Is there a way to streamline this to a single operation?

Kruse answered 9/2, 2013 at 20:57 Comment(2)
Using 'as' with null check is as streamlined as you will get.Sugar
See my suggestion below, use the Pre-processor:Parapsychology
C
4

No way to do this in a single operation.

However, using as and checking for null is cheaper as there is only one case instead of two as in your code sample.

Catalectic answered 9/2, 2013 at 20:59 Comment(1)
Keep in mind that this is more superior to the original code snippet you pasted not only because it does one cast, but also because it deals with situations where ctrl is a derivative of ControlTypeEtcWolfish
D
1

I would write it as:

ControlTypeEtc ctrl2 = ctrl as ControlTypeEtc;
if (ctrl2 != null)
    ctrl2.SomeMethod();

That avoids the double check (which may be optimized into one but I'm not sure).

Another way:

try
{
    ControlTypeEtc ctrl2 = (ControlTypeEtc)ctrl;
    ctrl2.SomeMethod();
}
catch (InvalidCastException e)
{
}
Doggo answered 9/2, 2013 at 21:3 Comment(0)
N
1

Bottom line is, "Big picture" you should know if your instance is null before you proceed coding against it. there really is no reason to find a shortcut around that step.

That said, if you are using C# 3 or better you have Extensions methods which can be used to "hide" this detail from the main logic of your code. See below the sample with 'SomeType' and 'SomeMethod' and then an extension method called 'SomeMethodSafe'. You can call 'SomeMethodSafe' on a Null reference without error.

Don't try this at home.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeType s = null;
            //s = new SomeType();
            // uncomment me to try it with an instance

            s.SomeMethodSafe();

            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }

    public class SomeType
    {
        public void SomeMethod()
        {
            Console.WriteLine("Success!");
        }
    }

    public static class SampleExtensions
    {
        public static void SomeMethodSafe(this SomeType t)
        {
            if (t != null)
            {
                t.SomeMethod();
            }
        }
    }
}
Nesselrode answered 9/2, 2013 at 21:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.