ojek
ojek

Reputation: 10088

C# - initialize static class as non-static class?

I have this class:

[DataContract]
public class Connection
{
    [DataMember]
    public string UserName { get; set; }

    public Connection(string userName)
    {
        UserName = userName;
    }
}

Now I need this class as-is, but in part of my project I would really use class like this:

public static class Connection
{
    public static string UserName { get; set; }

    static Connection()
    {
    }
}

Is there any way of merging this code together, so I can use both versions of this class in my project (somewhere I want to have a static, single instance of Connection, but somewhere else I want to have a list of Connections)?

Upvotes: 0

Views: 130

Answers (2)

Alexander Simonov
Alexander Simonov

Reputation: 1584

You can merge code like this:

[DataContract]
public class Connection
{
    [DataMember]
    public string UserName { get; set; }

    public Connection(string userName)
    {
        UserName = userName;
    }

    public static Connection Default { get; set; }

    static Connection()
    {
        Default = new Connection("username");
    }

}

... and use it like this:

List<Connection> connections = new List<Connection>();

.. or like this:

string defaultConnectionUserName = Connection.Default.UserName;

Upvotes: 5

JBeagle
JBeagle

Reputation: 2660

You cannot use a static class as a type argument. Therefore in your circumstance you cannot have:

public List<Connection> { get; set; }

See this answer by Jon Skeet for more information.

I suggest looking into the SOLID principles of object oriented programming and trying to abstract the functionality of the "connection" class out into multiples. If you provide more information on what you're trying to do I'll gladly make suggestions.

Upvotes: 0

Related Questions