Click here to Skip to main content
15,505,786 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
See more:
I get this question during an interview and I have no idea how to resolve it. I answered this is impossible to do but actually I don't know. I hope I will get smarter answer here than on stackoverflow.

Without modifying any of the code inside the main method, how can the can the following code be updated to prevent the NullReferenceException and also write 'Hello World' to the console?

C#
public class MyClass
{
}

public class Program
{
    static void Main(string[] args)
    {
        MyClass myObj = null;
        Console.WriteLine(myObj.GetString()); // Will throw NullReferenceException
    }
}


What is the solution to this question?
Posted
Updated 24-Aug-14 18:39pm
v2
Comments
[no name] 25-Aug-14 0:01am    
This code won't compile so it will never be able to throw an exception. If an interviewer asked me this without giving me the answer I would have a few doubts anyway.
Per Söderlund 25-Aug-14 1:08am    
Tell the interviewer to go to this thread and write a solution.
Would be fun to see.

If you are specifying null to the object itself and then invoking, what result would it give!! Dear this is not a right method to do, check for the null values and then look forward. You need change of code here without it, I dont think we can.
Thanks
:)
 
Share this answer
 
Comments
Bastien Vandamme 25-Aug-14 0:48am    
Yeah... you see it is why I ask the question. The interviewer ask me this question during my last interview. I also answered it was impossible.
[no name] 25-Aug-14 3:36am    
yes i guess the interviewer was confused too..:D
Try using Extension Methods:

C#
public class MyClass
{
}

public class Program
{
    static void Main(string[] args)
    {
        MyClass myObj = null;
        Console.WriteLine(myObj.GetString()); // Will throw NullReferenceException
    }
}

public static class Helper
{
    public static string GetString(this MyClass my)
    {
        return "hello world";
    }
}

//If .NET 2.0
//namespace System.Runtime.CompilerServices
//{
//    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
//    public sealed class ExtensionAttribute : Attribute { }
//}
 
Share this answer
 
Comments
[no name] 25-Aug-14 1:59am    
Very clever.
vikinghunter 25-Aug-14 4:55am    
Thx
There really isn't a way to make it work within the bounds specified.

No matter what you do to the MyClass class, you will always get the NullReference exception in Main.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 25-Aug-14 0:04am    
Agree, 5ed. This "question" is just a waste of time.
—SA
_Amy 25-Aug-14 1:38am    
Exactly, +5!
C#
if  (myObj == null)
   DoSomethingElse(); // :-)

—SA
 
Share this answer
 
Comments
Bastien Vandamme 24-Aug-14 23:38pm    
Without modifying any of the code inside the main method
Sergey Alexandrovich Kryukov 25-Aug-14 0:02am    
Oh, would you stop talking nonsense?
—SA
Bastien Vandamme 25-Aug-14 2:48am    
Where do you write your alternative if?
_Amy 25-Aug-14 1:39am    
+5!
Sergey Alexandrovich Kryukov 25-Aug-14 2:30am    
Thank you, Amy.
—SA
I think if we try using an attribute to handle the exception then on then exception handling lets actually return the Hello World string.
Creating an attribute something like the below.
[HandleExceptionAndReturnString]
 
Share this answer
 
v2
Comments
Bastien Vandamme 25-Aug-14 0:17am    
With attribute you can change the behavior of your method with reflection at run time. But this is the static main class. The one that is executed before all others...
Rajiv Gogoi 25-Aug-14 0:22am    
What I am saying is method level attribute which would apply at the static void main() method. It should be an exception handling attribute which does nothing but returns a hello world string whenever an exception occurs. Thats what we want, right .
Remove the static keyword on Main and rewrite the Program Class?
Like this.
public class MyClass
{
    public string GetString()
    {
        return "Hello World";
    }
}
class Program
{
void Main (string[] args)//Removed the static keyword
{
        MyClass myObj = null;
        Console.WriteLine(myObj.GetString());
    }
    public static void Main()//Created a new Main method
    {
        MyClass myObj = new MyClass();
        Console.WriteLine(myObj.GetString());
    }
}

Seriously though, there is no anchor to reality in this question and normally i wouldnt answer but i cant help it (I wanna play the game).
Anywho, I did not change anything INSIDE the main method,at least not within its scope.
 
Share this answer
 
Comments
[no name] 25-Aug-14 2:10am    
You have changed code inside the static Main() - no good.
Per Söderlund 25-Aug-14 2:13am    
I have not, I change static Main(string[] args) into non static.
Then created a new static Main()
There is one solution

Without modifying any of the code inside the main method,
but we can modify the MyClass right?

If yes then you can modify the MyClass and handle the exception there.

C#
public  class MyClass
    {
        public  string GetString()
         {
           try{
               return "Hello world";
              }
           catch(exception ex){
                // handle your exception here
                }
         }
    }


This type of questions interviewers ask when he/she wants to see your ability to solve problems. and how you handles difficult situation and do you find any alternative solutions or not.

Please mark it as solution if it helps
 
Share this answer
 
v3
Comments
[no name] 25-Aug-14 2:05am    
One cannot instantiate a static class. Did you test this? This is also a good attribute to have.
Bastien Vandamme 25-Aug-14 2:53am    
This won't work because my reference to myObj is still null in my main method. You know I'm pretty sure this is the solution my interviewer wanted but it's wrong. This type of questions interviewers ask when he/she wants to see your ability to solve problems but you have to ask right question first.
Ranjeet Patel 25-Aug-14 5:00am    
Yes that's true.. sometime it happens what the interviewer ask they even don't know the solutions. and they want it from you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900