The idea behind this code is that it uses an extension method to instantiate the class if this class is set to null. The code is simple enough, but it doesnβt work (it compiles and runs, but at the end the reference to the object is still null ).
Can someone tell me why?
The following code uses the simple SomeClass class, which has one string property.
class SomeClass { public string SomeProperty { get; set; } } static class ExtensionMethods { public static void InitialiseObjectIfNull<T>(this T obj) where T : class, new() { if (obj == null) obj = new T(); } } class Program { static void Main(string[] args) { SomeClass someClass = null; someClass.InitialiseObjectIfNull();
(A discussion of the appropriateness of using the extension method should be considered outside the scope of the question! I am interested to understand why this approach does not work)
Edit
On closer inspection, this question is less about extension methods and more about what happens when you pass a reference type with or without the ref keyword.
The following function will initialize the past obj for the caller:
static void InitialiseObjectIfNull<T>(ref T obj) where T : class, new() { if (obj == null) obj = new T(); } InitialiseObjectIfNull<SomeClass>(ref someClass);
The following function will not initialize the past obj for the caller:
static void InitialiseObjectIfNull<T>(T obj) where T : class, new() { if (obj == null) obj = new T(); } InitialiseObjectIfNull<SomeClass>(someClass);
But ... we are dealing with a reference type here, so what does the CLR do with new d obj if the ref keyword is not used? Presumably, he just gets the garbage collected ...
Edit2
Ok, we will get back to the basics here. Consider the following code:
class Program { static void SetProperty(SomeClass someClass) { someClass.SomeProperty = "Bar"; } static void Main(string[] args) { SomeClass someClass = new SomeClass { SomeProperty = "Foo" }; SetProperty(someClass);
Note: SomeClass not passed using the ref keyword, but its property value was still changed for the caller. This is what I expect to see.
However, modify the SetProperty function as follows:
static void SetProperty(SomeClass someClass) { someClass = new SomeClass { SomeProperty = "Bar" }; }
... and the caller will not see any changes in SomeClass .