Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing property in class without instantiation

Tags:

c#

class

Lets say I have a class:

public class foo
{

    public string bar 
    {
        get { return "A Value"; }
    }
}

If i only want to access the value contained in bar, and i wasn't interested in the actual class I could do something like:

string value = new foo().bar;

Is this really the best way of accessing the value? I don't want to make this property (and class) static.

If I had many classes with the bar property that I wanted to access, would there be a more generic way of doing it?

Edit: The reason why its not static is that its an overridden property, which i believe cannot be static:

public class parent
{
    public abstract string bar { get; }
}

public class foo : parent
{
    public override string bar
    {
        get { return "A Value"; }
    }
}
like image 501
user1838662 Avatar asked Oct 20 '25 01:10

user1838662


2 Answers

You need to use static which allows for methods and properties without an instance:

public class foo
{
    public static string bar 
    {
        get { return "A Value"; }
    }
}

There's no other way (other than consts and that's limited in a sense) that I know of having non-instance members.

like image 123
Lloyd Avatar answered Oct 21 '25 14:10

Lloyd


Based on your example I assume the value is a constant one, so instead of using a static property, you can use a const (which is about the same but more explicit):

public class Foo
{
    public const string Bar = "A value";
}

and access it with:

string value = Foo.Bar;

...but it depends on what you want to do with this variable - so maybe you can elaborate on that.

In any case, sometimes static variables have their uses, but don't overdo it. I personally always try to avoid statics as much as possible (in particular static operations) for a number of reasons, for example, see static facade in this post.

Also note that public properties and class names should follow Pascal notation, so it should be Bar and Foo.

An alternative option is to inject a provider component that provides you with the value. The dependency injection container takes care of this, and you could specify the correct lifetime for it at startup of your application. The default implementation (which gets the value from a configuration file for example) could then easily be replaced. Again, it all depends how far you want to go with this and how complex this 'value' is, if it's only a string, keep it simple :)

like image 26
L-Four Avatar answered Oct 21 '25 14:10

L-Four



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!