I have summarized my problem in following code snippet.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication13
{
public class Student
{
public int Marks { get; set; }
public Student(int marks)
{
this.Marks = marks;
}
public void AssignMarks(Student st)
{
st = null;
}
public void AssignMarks(ref Student st)
{
st = null;
}
}
class Program
{
static void Main(string[] args)
{
Student st = new Student(50);
st.AssignMarks(st);
Console.WriteLine(st.Marks);
Student st1 = new Student(50);
st.AssignMarks(ref st1); // NullReferenceException
Console.WriteLine(st1.Marks);
}
}
}
Why am I getting NullReferenceException exception on the line marked with the **
You’re actually getting the exception on the
WriteLinecall., (I tried it)Because
st1is passedref, the variable that you pass becomesnull.A
refparameter is a reference to a variable, not a reference to an object.Therefore, if a method changes its
refparameter to point to a different object, the variable whose reference was passed will be changed.