Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Type in field/variable

Tags:

c#

static

field

How can I store a Type in a static field, so that I can do something like this (note: just an example, in pseudocode)?:

public class Logger
{
    public static Type Writer;

    public static void SetWriter(Type @new)
    {
        Writer = @new;
    }

    public static void Write(string str)
    {
        Writer.Write(str);
    }
}
like image 410
Jwosty Avatar asked Jul 17 '12 00:07

Jwosty


2 Answers

Very simple:

Type variableName = typeof(SomeTypeName);

or

Type variableName = someObject.GetType();

Not sure this will help with what you actually want to do, though. See the other answers.

like image 77
Andrew Cooper Avatar answered Nov 18 '22 09:11

Andrew Cooper


Except for the fact that new is a keyword, your code to store the type should work fine.

However, your code

Writer.Write(str);

is meaningless.

The class Type does not have a method Write(string).

It feels like what you are after is an interface

public interface IWriter
{
    public Write(string text);
}

public class Logger
{
    public static IWriter Writer;

    public static void SetWriter(IWriter newWriter)
    {
        Writer = newWriter;
    }

    public static void Write(string str)
    {
        Writer.Write(str);
    }
}

That way, you would pass any class that implements IWriter into SetWriter, e.g.

public class MyWriter : IWriter
{
    public void Write(string text)
    {
        // Do something to "write" text
    }
}

Logger.SetWriter(new MyWriter());
like image 43
Eric J. Avatar answered Nov 18 '22 10:11

Eric J.