Click here to Skip to main content
15,910,603 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi all.

I have this piece of code and an extension method:

C#
class Program
   {
       public static TestClass TestClass { get; set; }

       static void Main(string[] args)
       {
           TestClass.New<TestClass>();
       }
   }

   class TestClass
   {

   }

   static class ObjectExtensions
   {
       public static T New<T>(this T instance)
       {
            instance = Activator.CreateInstance<T>();
            return (T)instance;
       }
   }


TestClass property is null.

Could someone please explain why this is null?

Context: Basically I want to create an extension method to create a new instance of any type:
This method will replace the coventional TestClass = new TestClass();

Much appreciated

Charles
Posted

Extension methods pass by value, so setting instance in the method does nothing. You can assign the returned value like this:

C#
static void Main(string[] args)
{
    TestClass = TestClass.New<TestClass>();
}


but why would you want to do that as opposed to just using new?
 
Share this answer
 
v3
Hey Shelby
Cheers for that mate: I wasn't aware that extension methods pass by value only.

My reasoning behind it: was just trying to see if could shoreten the new TestClass();

There tons of other ways but wanted to try with extension methods.
 
Share this answer
 
Comments
Ron Beyer 20-May-13 11:29am    
Just FYI, your extension methods don't make it shorter (in fact, there are more characters), and how would you support constructors with parameters? Also, your extension methods add significant overhead, if you run a performance test I would bet that your extension methods are 10-15 times slower than just using the normal "new" syntax. Just because its textually shorter, doesn't mean it works any better. Add on top of that the coder who has to come behind you and work on your cryptic code, it can make for a nightmare. Even if you are just playing around for your own amusement, develop habits that can work FOR you in the future, not against 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