"is" keyword when casting and then check null - c#

I'm new to C#, just a question on the use of "is" keyword.
I saw one of my textbook was using:
if (obj is Person && obj != null)
{
...
}
but is obj != null redundant?

The is keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type.
if (obj is Person) {
// Do something if obj is a Person.
}
You can also check for null.
So don't perform a null check.
var obj = new object();
Console.WriteLine(obj is null);
In this case else part will execute.
object obj = null;
if(obj is CustomData)
{
Console.WriteLine("Match");
}
else
{
Console.Write("Null");
}
Although useful, I would really advise not using it and instead, use as. The as keyword is a defensive cast, which means that a cast will be attempted and if the object is not able to be cast to the supplied type null is returned instead.
The reason I’d advise against using it because it will actually cause you to perform 2 casts – one to check if the object is of the type and then a second to actually capture the casted value.
Refer This
Refer This

I think very simply explain to you here
Person obj = new Person();
if (obj is Person && obj!=null){};
Is check the type and it will return a bool that is true or false. Is an operator never throw an error. Is refer metadata find out the type an object is found then it will return true otherwise return false.
Person obj = null;
if (obj is Person){//return always false}
if you try above code is return always return false.
obj!=null
!= is inequality operator if its operands are not equal it will return true otherwise false.
refer documentation "Is"
Equality Operator

Related

what does the questionmark do when typing object?.field? [duplicate]

With C# 6.0 in the VS2015 preview we have a new operator, ?., which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
What exactly does it do?
It's the null conditional operator. It basically means:
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.
In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}
... except that a is only evaluated once.
Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Model4 == null
|| Model.Model2.Model3.Model4.Name == null)
{
mapped.Name = "N/A"
}
else
{
mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)
mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
Action<TValue> myAction = null;
if (myAction != null)
{
myAction(TValue);
}
It can be simplified to:
myAction?.Invoke(TValue);
DotNetFiddle Example:
using System;
public class Program
{
public static void Main()
{
Action<string> consoleWrite = null;
consoleWrite?.Invoke("Test 1");
consoleWrite = (s) => Console.WriteLine(s);
consoleWrite?.Invoke("Test 2");
}
}
Result:
Test 2
Basically, I have applied ?. operator after Model as well. I am trying to know that whether it can be applied directly to the model or does it only work with the navigation properties?
The ? or null conditional operator operators on the left value, regardless of the type of value. And the compiler doesn't care what the value is on the right. It's simple compiler magic (meaning it does something you can already do, just in a simplified why).
For example
var a = model?.Value;
is the same as saying
var a = model == null ? null : model.Value;
In the second case the evaluation of checking for null has no associate with the value returned. The null conditional operator basically just always return null if the left value is null.
The type of member (Method, Field, Property, Constructor) .Value is irrelevant.
The reason your DotNetFiddle example doesn't work is because the compiler being use for the .Net 4.7.2 isn't compatible with the c# version that support the null conditional operator. Changing it to .Net 5, works:
https://dotnetfiddle.net/7EWoO5
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.

Returning null or a value in C#

I come from a strong Java background and I am very used to this kind of code:
Object o = foo();
if (o == null) {
bar();
} else {
somethingElse();
}
public Object foo() {
//code....
if (..) {
return Object;
} else {
return null;
But c# does not allow this. I want a function that returns an object if it has been found or return null if there is not such instance. What is the way to go about it in c#?
Have you tried doing this in C#? The code you posted should work exactly the same way in C#, and there's no reason to think that a simple null check would be different.
However, unlike Java, C# also offers a more idiomatic way of handling nulls. C# has the ?? operator, which is fairly similar to the ternary ? operator, but checks for null.
Object o = foo();
Object result = o ?? somethingElse();
That snippet will call foo() and assign it to result if o is NOT null, or call somethingElse() if o is null.
Note that for value types, C# has the concept of nullable types, unlike Java. In Java,
int x = null;
is not valid. It's also not valid in C#, but you can create a nullable int. That means a value type (int in this case) that can also have null as a value.
int? x = null;
That is valid C# code.

Why is ReSharper suggesting a possible NullReferenceException on a dynamic type?

If I write the following code, ReSharper is warning me for a possible NullReferenceException. However I'm explicitly checking for null in the statement above. Is there something about dynamic I do not know about (is it assuming it might be backed by a IEnumerable or something like that)? Or is this a glitch with ReSharper? Or something else?
dynamic user = connection.Query("SELECT ...").FirstOrDefault(); // Dapper Extension
if (user == null)
return null;
return new User(user.username);
// ^^^^
// (local variable) dynamic user
//
// Possible 'System.NullReferenceException'
The issue is that user == null is a dynamic call; R# can't assume that the runtime type of the user object will have an equality operator that works properly. It could very easily have:
public static bool operator ==(Foo x, Foo y) { return false; }
public static bool operator !=(Foo x, Foo y) { return true; }
in which case, user == null would always return false, even if the user variable was a null reference.
Try changing the code to:
if (ReferenceEquals(user, null)) return null;
return new User(user.username);
NB: The problem only appears when you have the "Assume entity value can be null" option set to "When entity doesn't have explicit NotNull attribute".
Try this :
dynamic user = connection.Query("SELECT ...").FirstOrDefault(); // Dapper Extension
if (user != null)
return new User(user.username);
return null;

Should we check NULL when cast IClass to Class?

Question 1> Should I check NULL in the following case?
public interface INewClass {}
public class NewClass : INewClass {}
public void FunMeA(INewClass obj)
{
NewClass n = (NewClass) obj;
... // Should I check (n == null) here?
// call methods defined inside INewClass (updated from NewClass to INewClass)
...
}
A concrete example,
public void FunMeB(IAsyncResult itfAR)
{
AsyncResult ar = (AsyncResult) itfAR;
... // Should I check (ar == null) here?
// access ar.AsyncDelegate
...
}
Question 2> I just start to transfer to C# from C++.
When coding in C++, I know when the checking should be done.
However, I am totally lost in the C# world. So the question is: is there
a general rule that can tell me when I MUST check for NULL?
Thank you
When doing this:
NewClass n = (NewClass) obj;
There is no point, because if it doesn't cast it will throw an invalid cast exception.
If you have any doubts as to whether or not you can actually cast it, you want to do:
NewClass n = obj as NewClass;
then
if(n != null) ...
The cast you are doing is called a direct cast, where the system will assume that it can be made. the n = obj as NewClass is called an indirect cast and is for those scenarios where you want to tell the program "Hey I think this will work, but if not don't flip out and throw an exception...I'll deal with it if it doesn't work."
Using is vs as in casting.
Depending on which scenario you want one will be better than the other. Technically from a performance perspective as is preferred. .Net will use atomically attempt to cast to the desired type and return null if it's not, where with is it will have to walk the inheritance tree twice to see if it matches that type and then cast it. So in most cases if you want to see if you want to cast and use that type it's better to:
var obj = o as type
if (obj != null)
as opposed to
if(o is type)
{
var obj = (type);
}
If the cast fails, your code will throw an exception.
Use the is operator to see if a cast will work, and as to cast (which will not throw and return a null if the cast fails).
So:
if(obj is NewClass)
{
//Yay, can cast!
}
Or:
NewClass nc = obj as NewClass;
if(nc != null)
{
//Yay!
}
If you want to check for null then you should do
NewClass n = obj as NewClass ;
if (n != null)
{
...
}
But in general you could check for null if that means something to in the context and you can take alternative actions. In most cased, you should just let it throw NullReferenceException rather than swallowing it so you can identify the cause of the null reference faster.
If you do NewClass n = (NewClass)obj you'll get an exception thrown if it doesn't cast properly.
If you want there to be a possibility of it being null, without throwing an exception, you'd want to do NewClass n = obj as NewClass; and then check if n is null.
You can check if a cast is going to work before hand, by using the is operator.
if(obj is NewClass)
Hope this helps.
If the parameter is required, you should always check for null and throw an ArgumentException or ArugmentNullException.
The best way for this parameter check here is:
AsyncResult ar = itfAR as AsyncResult;
if(ar == null)
{
// even better: Use a resource here
throw new ArgumentNullException("Parameter itfAR must not be null and must be of type AsyncResult");
}
I prefer to check to for null before the cast. E.g.
if (obj == null)
{
throw new ArgumentNullException("obj", "The argument must has a value specified");
}
Your are mixing up to issues.
You should always validate arguments to a publicly exposed method. Therefore you sould first do:
public WhateEverMethod(IElement iElement)
{
if (iElement == null)
{
throw new ArgumentNullException(...);
}
}
Once you have validated that element is not null you check if you can perform the cast. You can go two ways essentially:
Element element = iElement as Element;
if (element == null) //cast failed
{
throw new InvalidCastException(...);
}
or
if (!(iElement is Element))
{
throw new InvalidCastException(...);
}
Element element = (Element)iElement;

Difference between is and as keyword

Please tell what is the difference between is and as keyword in C#
is
The is operator checks if an object can be cast to a specific type.
Example:
if (someObject is StringBuilder) ...
as
The as operator attempts to cast an object to a specific type, and returns null if it fails.
Example:
StringBuilder b = someObject as StringBuilder;
if (b != null) ...
Also related:
Casting
The cast operator attempts to cast an object to a specific type, and throws an exeption if it fails.
Example:
StringBuilder b = (StringBuilder)someObject.
The Difference between IS and As is that..
IS - Is Operator is used to Check the Compatibility of an Object with a given Type and it returns the result as a Boolean (True Or False).
AS - As Operator is used for Casting of Object to a given Type or a Class.
Ex.
Student s = obj as Student;
is equivalent to:
Student s = obj is Student ? (Student)obj : (Student)null;
Both is and as keywords are used for type casting in C#.
When you take a look at the IL code of usages of both the keywords, you will get the difference easily.
C# Code:
BaseClass baseclassInstance = new DerivedClass();
DerivedClass derivedclassInstance;
if (baseclassInstance is DerivedClass)
{
derivedclassInstance = (DerivedClass)baseclassInstance;
// do something on derivedclassInstance
}
derivedclassInstance = baseclassInstance as DerivedClass;
if (derivedclassInstance != null)
{
// do something on derivedclassInstance
}
IL code (for above C# code is in the attached image):
The IL code for is keyword usage contains IL instructions both isinsta and castclass.
But the IL code for as keyword usage has only isinsta.
In the above mentioned usage, two typecast will happen where is keyword is used and only one typecast where as keyword is used.
Note: If you are using is keyword to check some condition and do not have any interest in the typecast result, then there will be only one typecast, i.e.
if (baseclassInstance is DerivedClass)
{
// do something based on the condition check.
}
is and as keywords will be used based on the necessity.
The is keyword checks whether the value on its left side is an instance of the type on the right side. For example:
if(obj is string)
{
...
}
Note that in this case you'll have to use an extra explicit cast to get obj as string.
The as keyword is used to cast nullable types. If the specified value is not an instance of the specified type, null is returned. For example:
string str = obj as string;
if(str != null)
{
...
}
is OPERATOR
The is operator in C# is used to check the object type and it returns a bool value: true if the object is the same type and false if not.
or also The “is” operator is used to check whether the run-time type of an object is compatible with a given type or not.
For null objects, it returns false
e.g
if(obj is AnimalObject)
{
//Then Work
}
as OPERATOR
The as operator does the same job of is operator but the difference is instead of bool, it returns the object if they are compatible to that type, else it returns null.In otherwords, The ‘as‘ operator is used to perform conversions between compatible types.
e.g
Type obj = Object as Type;
Advantages of as over is
In case of is operator, to type cast, we need to do two steps:
Check the Type using is
If it’s true then Type cast
Actually this affects the performance since each and every time the CLR will go through the inheritance hierarchy, checking each base type against the specified type.
To avoid this, use as, it will do it in one step. Only for checking the type should we use the is operator.
I would say: read MSDN online, but here it is:
The is operator checks whether an object is compatible with a given type, and the result of the evaluation is a Boolean: true or false.
The as operator will never throw an exception.
Is operator , a cast, returns true if it succeeds. It returns false if the cast fails. With it, you cannot capture the converted variable. This operator is most useful when checking types in if-statements and expressions.The is-cast is only ideal if the resulting variable will not be needed for further use
As is a cast. With it, we gain performance and avoid exceptions when a cast is invalid. Null is returned when the cast is impossible. For reference types, the as-cast is recommended. It is both fast and safe.We can test the resulting variable against null and then use it. This eliminates extra casts
is operator checks whether the object is compatible with the given
type the result based upon true or false.
as is used to cast one type to another type and on conversion
failure results null except then raising exception.
well see link for better understanding with examples https://blogs.msdn.microsoft.com/prakasht/2013/04/23/difference-between-direct-casting-is-and-as-operator-in-c/
The As operator is similar to a cast, but returns null instead of an exception if it fails.
And the Is operator is used to check if one object is compatible with a certain type. It's usually used in If statements.
is: The is operator is used to check whether the run-time type of an object is compatible with a given type
as: The as operator is used to perform conversions between compatible types.
object s = "this is a test";
string str=string.Empty;
if( s is string)
str = s as string;
MyClass myObject = (MyClass) obj;
vs
MyClass myObject = obj as MyClass;
The second will return null if obj isn't a MyClass, rather than throw a class cast exception.
is will only return true or false
Both IS and AS are used for Safe Type Casting
IS Keyword-->
checks whether the type of an given object is compatible with the new object type. It Never Throws an exception. This is a Boolean type..returns either true or false
`student stud = new student(){}
if(stud is student){} // It returns true // let say boys as derived class
if(stud is boys){}// It returns false since stud is not boys type
//this returns true when,
student stud = new boys() // this return true for both if conditions.`
AS Keyword:
checks whether the type of an given object is compatible with the new object type. It returns non-null if given object is compatible with new one, else null.. This throws an exception.
`student stud = new student(){}
// let say boys as derived class
boys boy = stud as boys;//this returns null since we cant convert stud type from base class to derived class
student stud = new boys()
boys boy = stud as boys;// this returns not null since the obj is pointing to derived class`
Both operator are used for safe type casting.
AS Operator :
The AS operator also checks whether the type of a given object is compatible with the new object type. This keyword will check whether the type of a given object is compatible with the new object type. If it's not compatible with the new one then it will return NULL.
IS Operator:
This Operator checks whether the type of an object is compatible with the new object. If it's compatible it returns true otherwise false.

Categories