Search code examples
.netvb.net

Can we have Class.Empty Object like we have in String.Empty


I am using .NET 3.5. I am creating a simple class and wants to make sure that the class after processing should not be null or should not be a new too..

So if we can just Test it like that

Dim objClass as new Class()

' do some processing with the class '
' and then.. check that if this object returned is not empty '

If (objClass = Class.Empty) Then
//Do stuff
Else
//Do Other Stuff
End If

is there a way we can create this empty Field like we have in String.Empty?


Solution

  • But in your example the class isn't technically empty. You've created an instance of Class using the default constructor. Who knows, the default constructor may have initialised over 10MB of string content. What your code is technically checking is, is the class equal to it's default state just after being constructed.

    See this for example of VB constructors and what is happening.

    If you correctly implemented CompareTo(...) you could call

    If (objClass.CompareTo(new Class()) == 0) Then 
     //Do stuff 
    Else
     //Do Other Stuff 
    End If 
    

    But that would seem overkill / expensive, but the only way it would work.

    Another option would be: (sorry c# based example)

    Interface IEmpyClass
    {
       bool IsEmptyClass{get;}
    }
    
    public class Class : IEmptyClass
    {
       public bool IsEmptyClass{get; private set;}
    
       public Class()
       {
         IsEmptyClass = true;
       }
    
       public void DoSomething()
       {
           // Do something
           IsEmptyClass = false;
       }
    }
    

    You would be responsible for implementing the example and changing the property when the class state changed from "empty", but that would be quicker in code, etc. and could cope when clases have constructors with members. It could be checked just with

    If (objClass.IsEmptyClass) Then 
     //Do stuff 
    Else
     //Do Other Stuff 
    End If