Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to mark a method as ensuring that T is not null?

For example, if I have a method defined as...

T Create()
{
    T t = Factory.Create<T>();

    // ...

    Assert.IsNotNull(t, "Some message.");
    // -or-
    if (t == null) throw new Exception("...");
    // -or- anything that verifies that it is not null
}

...and I am calling that method from somewhere else...

void SomewhereElse()
{
    T t = Create();
    // >><<
}

...at >><<, I know (meaning me, the person who wrote this) that t is guaranteed to not be null. Is there a way (an attribute, perhaps, that I have not found) to mark a method as ensuring that a reference type that it returns or otherwise passes out (perhaps an out parameter) is guaranteed by internal logic to not be null?

I have to sheepishly admit that ReSharper is mostly why I care as it highlights anything it thinks could cause either InvalidOperationException or NullReferenceException. I figure either it's reading something that I can mark on my methods or it just knows that Assert.IsNotNull, simple boolean checks or a few other things will remove the chance of something being null and that it can remove the highlight.

Any thoughts? Am I just falling victim to oh-my-god-resharper-highlights-it-I-have-to-fix-it disease?

like image 603
Shibumi Avatar asked Mar 15 '11 19:03

Shibumi


People also ask

How do you make sure an object is not null?

Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .

How do you write NOT null condition in C#?

C# | IsNullOrEmpty() Method In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.

IS null condition C#?

The null conditional is a form of a member access operator (the .). Here's a simplified explanation for the null conditional operator: The expression A?. B evaluates to B if the left operand (A) is non-null; otherwise, it evaluates to null.


1 Answers

If ReSharper is why you care then you can mark the Factory.Create<T>() method with their [NotNull] attribute described in their web help

like image 190
Mike Two Avatar answered Nov 16 '22 02:11

Mike Two