Generic method returns nullReferenceException - c#

I have this Generic Method that always returns a nullReferenceException. I've taken all the unnecessary code out, and it still give me the exception.
public T RetrieveInformationFromApi<T>(int Id) where T : IMovie
{
T result = default(T);
result.Title = "test";
}
The method can be called with three different classes that all have the attribute Title and the all implement the interface IMovie but the method still give me an exception. What am i doing wrong?

You should add a constructor constraint on you T parameter so you can create a new instance.
public T RetrieveInformationFromApi<T>(int Id) where T : IMovie, new()
{
T result = new T();
result.Title = "test";
}

You're using default which returns null for reference types (and I'm guessing you're using a reference type.
From MSDN:
Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types.
I'm not sure what you're trying to achieve but this way you will always get that exception for reference types.

When the T is a reference type (class), the default (T) returns null, as it is the default value of all reference types.
Then obviously trying to access its property results in NullReferenceException

Related

C# access to stack object property

How can I access the objects property in this situation?
Araba araba = new Araba();
araba.Renk = "mavi";
araba.fiyat = 12345;
// I created this class and it working normally
ArrayTypedStack asd = new ArrayTypedStack(10);
asd.Push(araba);
object araba2 = asd.Pop();
araba2. //cant access
Here you are assigning the value of asd.Pop() to a variable of the type object.
object is the root of all objects (all objects inherit from it and can be casted to it) and as such has no real information about what it is. It's just like any object in real life is a thing.
The solution here is to declare the araba2 as the type Araba, that will give you access to all the properties on the next line.
I don't know the implementation of the ArrayTypedStack and what the Pop() method looks like (it's return type) so it's possible that this will give you an error, saying that it can't convert an object to the type Araba. This is the type safety implemented in .NET. You have to convince .NET that it's of the type Araba, this can be by casting
Araba araba2 = (Araba)asd.Pop();
this can still give an error on runtime if the object returned from Pop() isn't of the type Araba, in this case you can ask .NET to try to cast it, there are serveral options for this:
object popResult = asd.Pop();
if (popResult is Araba) {
Araba araba2 = (Araba)popResult;
}
// can be written as follows:
if (popResult is Araba araba3) {
araba3.fiyat = 65432;
}
// can also be done as follows
Araba araba4 = asd.Pop() as Araba;
if (araba4 != null) {
araba4.fiyat = 84368;
}
Well, your araba2 variable is of type object. Thus, regardless of the actual type of the instance it contains, through the object variable araba2 you can only access members that are provided by the type object.
To access members provided by the Araba type (and assuming the instance in the araba2 variable is an instance of type Araba), the araba2 variable itself should be of type Araba, or the value of araba2 needs to be cast as Araba.
Thus,
var araba2 = asd.Pop();
or
var araba2 = (Araba) asd.Pop();
with the first example code line above requiring that the return type of the Pop method is Araba (or a type derived from Araba). The latter code line example will work regardless of the return type of Pop as long as the value returned by Pop is an actual Araba instance (or is something that is convertible to an Araba instance).

How to check if deserealized class members have value?

I have an initial snippet which deserealized parameters, checks for value and handles the error:
var param = js.Deserialize<int?>(jqData.Params);
if (param.HasValue)
{
resp.ReturnValue = param.Value;
}
else
{
//handle error code
}
Now, during my modification, I have changed the method to accept a list of class parameters instead of nullable integers
var param = js.Deserialize<ClassName>(jqData.Params);
Now it invalidates .HasValue and .Value methods.
My question is: How do I properly modify these two lines so it would hold the same meaning as initial if statement?
Thus far I only thought about switching to if (param != null), but I cannot think of proper equivalent to .Value.
As soon as ClassName is a class (see - a reference type) you just need to check if it is not null.
If it is not - then the variable holds a reference to an object that you use as-is.

How to Cast A Variable Using Generic Type Parameter and 'as' Operator

I have the following generic static class which is being used in a Fluent API. It takes an input parameter and returns a wrapper class containing the parameter cast to the generic type.:
public static Foo<TOut> InputAs<TOut>(object parameter) {
var castParameter = parameter as TOut;
if(castParameter == null) {
throw new Exception("Invalid cast");
}
return new Foo<TOut>(castParameter);
}
The problem is that the castParameter == null check always returns null. What would be the correct way to cast the object using the TOut generic parameter as the new type?
Well, if parameter as TOut returns null, then the runtime type of parameter isn't TOut.
Don't forget that operator resolution is done at compile-time, so if you have cast operators defined, they will not be invoked here. If you do need that, you can use dynamic:
public static Foo<TOut> InputAs<TOut>(dynamic parameter)
{
return new Foo<TOut>((TOut)parameter);
}
This will allow runtime operator resolution, and will call your cast operator if one is available. For example, it will allow you to pass long, while expecting int.
However, you probably want to find a different way of what you're trying to do; dynamic can be very useful, but it can also make debugging quite a bit harder, and you lose almost all compile-time warnings and errors that can help you identify problems before they happen.

How to pass the current instance to FieldInfo.GetValue inside the instance?

I'm making an abstract class that I need to validate fields in it's descendants. All the validated fields are marked by an attribute and are suppose to be checked for nulls or empty. To do that I get all the fields in the class:
var fields = this.GetType().GetFields().Where(field => Attribute.IsDefined(field, typeof(MyAttribute))).ToList();
And then, for every FieldInfo I try to do this:
if (string.IsNullOrEmpty(field.GetValue(this).ToString()))
{
// write down the name of the field
}
I get a System.NullReferenceException: object reference not set to an instance of an object.
I know I am suppose to pass the instance of a class to the GetValue method. But how can I pass the current instance (the one that's launching the logic)?
Or: Is there an other way of getting the field's value?
As Lucas says, the problem will be calling ToString() when you shouldn't. Presumably your attribute should only be applied to string fields anyway, so the simplest approach is just to cast the result to string. If that cast fails, it indicates a bigger bug (the attribute being applied incorrectly).
if (string.IsNullOrEmpty((string) field.GetValue(this)))
The GetValue call is fine. The problem lies in the return value on which you're calling ToString.
If GetValue returns null, then ToString will be called on this null value, and this will throw the NullReferenceException.
Do something like this instead:
var value = field.GetValue(this);
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
// write down the name of the field
}

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