Alex Rivera | Logout

What hack can I use to define a C# property with same name as class?

Asked 2011-10-22T14:37:35.367
10

I'm using C# to make a .Net class library (a DLL) that will be distributed widely. I have an abstract class called Value, and I want it to have an abstract double property that is also called Value i.e.

public abstract class Value {

    // Only accessible by subclasses within the project.
    internal Value() {}

    public abstract double Value {
        get;
    }

}

But the C# compiler won't allow this - I get the message "member names cannot be the same as their enclosing type", as discussed here.

I understand that the easiest thing to do would be to change the name of the property or the name of the class... But really I want the names to be like that, and I'm quite happy to implement an ugly hack to get it that way. So long as it works properly from external code that uses this DLL.

Unlike C#, VB.Net will allow me to define a property with the same name as the class, so I'm currently investigating merging my C# project with a VB project that defines the Value class (and its Value property) to make one DLL. This doesn't seem to be quite as straightforward as I was hoping.

Another option would be to re-write the whole project in VB... Not very appealing, but I'll consider it if necessary. I prefer C# over VB.Net but my priority is to get the built DLL the way I want it.

I'm wondering what other alternatives there might be. Any ideas for a good way to hack this?

EDIT: From the comments below it's clear that quite a number of people don't think much of the name "Value" for a class... Could anyone explain why it's so bad? I know it's not very descriptive, but I think it fits well in the context of my project. Is it because it's a keyword in C# that's used in property setters?

Edit
Report

1 Answer

2

As other people have said, this is not possible in C#.

Other people have criticised the name Value as a class, and while I agree it's likely too generic, I can see situations where it may make sense.

Bearing that in mind, if Value is an abstract class, perhaps ValueBase might be a decent, conformant, name? Much of the .Net framework (particularly WPF) uses XxxBase.

Another option to consider is prefixing the class name with the name of your project, as in FooValue.

answered 2011-10-22T16:31:01.747

Your Answer