How to use Object.ReferenceEquals(null, myObjVar) to solve error object reference not set to an instance of an object ?

ahmed salah 3,216 Reputation points
2022-08-15T08:31:47.977+00:00

I work on csharp i get error object reference not set to an instance of an object

so how to use Object.ReferenceEquals(null, myObjVar) to solve error

code give me error

 var Data = result.items.Select(e => new { PartID = e.create._id, IsUpdated = e.create.error != null && e.create.error.reason !=null && !e.create.error.reason.Contains("document already exists") ? 0 : 1, ErrorStatus = e.create.error == null  | (e.create.error.reason!=null && e.create.error.reason.Contains("document already exists")) ? null : e.create.error.reason }).ToList();  

ElasticPartialUpdat.Create.error.get returned null.

How to use this lines below to solve error

if (Object.ReferenceEquals(null, myObjVar))  {    .......  }   
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,401 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,201 Reputation points
    2022-08-15T08:39:06.687+00:00

    Here is an example which should help.

    public class MonthData : IEquatable<MonthData>  
    {  
    	public string Month { get; set; }  
    	public int Index { get; set; }  
      
    	public override string ToString()  
    	{  
    		return $"{{ Month = {Month}, Index = {Index} }}";  
    	}  
      
    	public bool Equals(MonthData other)  
    	{  
    		if (ReferenceEquals(null, other)) return false;  
    		if (ReferenceEquals(this, other)) return true;  
    		return Month == other.Month && Index == other.Index;  
    	}  
      
    	public override bool Equals(object obj)  
    	{  
    		if (ReferenceEquals(null, obj)) return false;  
    		if (ReferenceEquals(this, obj)) return true;  
    		if (obj.GetType() != this.GetType()) return false;  
    		return Equals((MonthData) obj);  
    	}  
      
    	public override int GetHashCode()  
    	{  
    		return HashCode.Combine(Month, Index);  
    	}  
    }  
    

    It's always good to read the docs

    0 comments No comments