dbobrowski
dbobrowski

Reputation: 846

Static to instance, how do I handle properly?

I have a static class I am deprecating and modifying the class to force clients to use an instance variable.

Question is, how do I handle allowing the previous static class to remain and be used (with obsolete attribute) and also allow the new non static class to be used as well (same name, same method names)?

Is this possible?

Upvotes: 2

Views: 110

Answers (4)

Paolo Falabella
Paolo Falabella

Reputation: 25844

One thing you could do is to implement non-static versions of methods through an explicitly implemented interface, like this:

public interface ITest
{
    string Foo();
}

// your class
public class Test : ITest
{
    //original, static version of Foo
    public static string Foo() 
    {
        return "foo";
    }   

    // Foo reimplemented as a non-static method
    // note that you need to implement ITest explicitly
    // for it to compile
    string ITest.Foo()
    {
        return "foo";
    }   
}

This compiles and works as expected, except that the non-static methods can only be called through the interface, i.e.:

ITest t = new Test();   //assigning to a variable of type ITest
Console.WriteLine(t.Foo()); // writes "foo"
Console.WriteLine(Test.Foo()); // and calling the static method still works too

Upvotes: 0

PTiddy
PTiddy

Reputation: 126

Not possible with same class name and same members, the type would be ambiguous. This is frequently done using the obsolete attribute's message field to tell the caller what class to use instead, in this case, your new instance class.

You could come up with some convoluted versioned interface, perhaps, but even in the best case that would be unclear to callers and they would have to know which version they were dealing with. Callers need to handle an instace and static classes differently, so hiding which they are using would only lead to problems (were it possible to do so).

Upvotes: 0

Ali Khalid
Ali Khalid

Reputation: 1345

I don't think it will be possible to keep the same name and parameters but you could do this

[Obsolete("This class is obsolete; use class B instead")]

Visual Studio will hint to the user, that they should be using the new class.

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391496

There are several ways you can use, but none do exactly what you want:

  1. Remove the static modifier, making it a normal non-static class, and optionally make it partial, implementing the new instance related code in a second file. With this method, however, you will not be able to obsolete the entire static class, as you have only one class.
  2. Place the new class in a new namespace
  3. Place the new class in a new project, but in the same namespace as the original

If you make all the old static members obsolete, I would go for option nbr. 1.

Upvotes: 2

Related Questions