development

C #에서 개체가 null인지 확인

big-blog 2020. 5. 12. 19:10
반응형

C #에서 개체가 null인지 확인


객체가 null 인 경우 추가 처리를 방지하고 싶습니다.

다음 코드에서 객체가 null인지 확인합니다.

if (!data.Equals(null))

if (data != null)

그러나에 메시지가 표시 NullReferenceException됩니다 dataList.Add(data). 오브젝트가 널인 경우, if-statement를 입력하지 않아야합니다!

따라서 객체가 null인지 확인하는 적절한 방법인지 묻습니다.

public List<Object> dataList;
public  bool AddData(ref Object data)
    bool success = false;
    try
    {
        // I've also used "if (data != null)" which hasn't worked either
        if (!data.Equals(null))
        {
           //NullReferenceException occurs here ...
           dataList.Add(data);
           success = doOtherStuff(data);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }
    return success;
}

이것이 객체가 null인지 확인하는 올바른 방법이면 내가 뭘 잘못하고 있습니까 (NullReferenceException을 피하기 위해 객체에서 추가 처리를 방지하려면 어떻게해야합니까?)


그것은 아니에요 data입니다 nulldataList.

당신은 하나를 만들어야합니다

public List<Object> dataList = new List<Object>();

더 낫습니다 private. 필드이기 때문에 확인하십시오 . 그리고 당신을 방해하는 것이 없다면, 또한 그것을 만드십시오 readonly. 좋은 습관이야

곁에

무효 여부를 확인하는 올바른 방법은 if(data != null)입니다. 이러한 종류의 점검은 참조 유형에 대해 어디에나 있습니다. 심지어 Nullable<T>표현하는 더 편리한 방법이 항등 연산자를 대체 nullable.HasValue무효 확인시.

그렇게 if(!data.Equals(null))하면 NullReferenceExceptionif 을 얻게 됩니다 data == null. 이 예외를 피한 것이 처음부터 목표 였기 때문에 코믹한 것입니다.

당신은 또한 이것을하고 있습니다 :

catch (Exception e)
{
    throw new Exception(e.ToString());
}

이것은 확실히 좋지 않습니다. 메서드 안에 여전히있는 동안 디버거에 침입 할 수 있으므로이 단락을 무시한다고 생각할 수 있습니다. 그렇지 않으면 아무것도 예외를 포착하지 마십시오. 그리고 그렇게하면 just을 사용하여 다시 던지십시오 throw;.


C # 6에는 monadic null 점검이 있습니다. :)

전에:

if (points != null) {
    var next = points.FirstOrDefault();
    if (next != null && next.X != null) return next.X;
}   
return -1;

후:

var bestValue = points?.FirstOrDefault()?.X ?? -1;

C # 7에서 최고는

if (obj is null) ...

This will ignore any == or != defined by the object (unless of course you want to use them ...)

For not equal you can if (!(obj is null)) (ugly)


Your dataList is null as it has not been instantiated, judging by the code you have posted.

Try:

public List<Object> dataList = new List<Object>();
public  bool AddData(ref Object data)
bool success = false;
try
{
    if (!data.Equals(null))   // I've also used if(data != null) which hasn't worked either
    {
       dataList.Add(data);                      //NullReferenceException occurs here
       success = doOtherStuff(data);
    }
}
catch (Exception e)
{
    throw new Exception(e.ToString());
}
return success;

}


[Edited to reflect hint by @kelton52]

Simplest way is to do object.ReferenceEquals(null, data)

Since (null==data) is NOT guaranteed to work:

class Nully
{
    public static bool operator ==(Nully n, object o)
    {
        Console.WriteLine("Comparing '" + n + "' with '" + o + "'");
        return true;
    }
    public static bool operator !=(Nully n, object o) { return !(n==o); }
}
void Main()
{
    var data = new Nully();
    Console.WriteLine(null == data);
    Console.WriteLine(object.ReferenceEquals(null, data));
}

Produces:

Comparing '' with 'Nully'

True

False


No, you should be using !=. If data is actually null then your program will just crash with a NullReferenceException as a result of attempting to call the Equals method on null. Also realize that, if you specifically want to check for reference equality, you should use the Object.ReferenceEquals method as you never know how Equals has been implemented.

Your program is crashing because dataList is null as you never initialize it.


The problem in this case is not that data is null. It is that dataList itself is null.

In the place where you declare dataList you should create a new List object and assign it to the variable.

List<object> dataList = new List<object>();

In addition to @Jose Ortega answer, its better for use extension method

 public static bool IsNull(this object T)
     {
        return T == null;
     } 

And use IsNull method for all of object like:

object foo = new object(); //or any object from any class
if (foo.IsNull())
   {
     // blah blah //
   }

Jeffrey L Whitledge is right. Your `dataList´-Object itself is null.

There is also another problem with your code: You are using the ref-keyword, which means the argument data cannot be null! The MSDN says:

An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed

It's also not a good idea to use generics with the type `Object´. Generics should avoid boxing/unboxing and also ensure type safety. If you want a common type make your method generic. Finally your code should look like this:

public class Foo<T> where T : MyTypeOrInterface {

      public List<T> dataList = new List<T>();

      public bool AddData(ref T data) {
        bool success = false;
        try {
          dataList.Add(data);                   
          success = doOtherStuff(data);
        } catch (Exception e) {
          throw new Exception(e.ToString());
        }
        return success;
      }

      private bool doOtherStuff(T data) {
        //...
      }
    }

As others have already pointed out, it's not data but rather likely dataList that is null. In addition to that...

catch-throw is an antipattern that almost always makes me want to throw up every time that I see it. Imagine that something goes wrong deep in something that doOtherStuff() calls. All you get back is an Exception object, thrown at the throw in AddData(). No stack trace, no call information, no state, nothing at all to indicate the real source of the problem, unless you go in and switch your debugger to break on exception thrown rather than exception unhandled. If you are catching an exception and just re-throwing it in any way, particularly if the code in the try block is in any way nontrivial, do yourself (and your colleagues, present and future) a favor and throw out the entire try-catch block. Granted, throw; is better than the alternatives, but you are still giving yourself (or whoever else is trying to fix a bug in the code) completely unnecessary headaches. This is not to say that try-catch-throw is necessarily evil per se, as long as you do something relevant with the exception object that was thrown inside the catch block.

Then there's the potential problems of catching Exception in the first place, but that's another matter, particularly since in this particular case you throw an exception.

Another thing that strikes me as more than a little dangerous is that data could potentially change value during the execution of the function, since you are passing by reference. So the null check might pass but before the code gets to doing anything with the value, it's changed - perhaps to null. I'm not positive if this is a concern or not (it might not be), but it seems worth watching out for.


  public static bool isnull(object T)
  {
      return T == null ? true : false;
  }

use:

isnull(object.check.it)

Conditional use:

isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;

Update (another way) updated 08/31/2017. Thanks for the comment.

public static bool isnull(object T)
{
    return T ? true : false;
}

Whenever you are creating objects of class you have to check the whether the object is null or not using the below code.

Example: object1 is object of class

void myFunction(object1)
{
  if(object1!=null)
  {
     object1.value1 //If we miss the null check then here we get the Null Reference exception
  }
}

I just followed a method that we would usually follow in java script. To convert object to string and then check whether they are null.

var obj = new Object();
var objStr = obj.ToString();
if (!string.IsNullOrEmpty(objStr)){
  // code as per your needs
}

참고URL : https://stackoverflow.com/questions/6417902/checking-if-an-object-is-null-in-c-sharp

반응형