balazs
balazs

Reputation: 520

Is it possible to have "inherited partial structs" in c#?

Is it possible to use partial structs to achieve something like this: Have an asp.net page base class with the following defined:

public partial struct QuerystringKeys
{
    public const string Username = "username";
    public const string CurrentUser = "currentUser";
}

Have an asp.net page, which inherits from the base class mentioned above, extend the partial declaration:

public partial struct QuerystringKeys
{
    /// <summary>
    /// The page number of the review instances list
    /// </summary>
    public const string Page = "page";
}

The final goal is a QuerystringKeys struct with all three constant strings defined in it available to the asp.net page.

Upvotes: 1

Views: 876

Answers (3)

driis
driis

Reputation: 164281

No, you cannot do that. When you are taliking about the ASP .NET pages, I assume you want the struct to be contained within the page class declaration (if not, why don't you just put it in a separate code file) ?

If your struct is only intended to hold constant strings, use a class and inherit from the base. Since you won't be creating instances of it, there will be no difference:

public class Test : Page
{
    internal class QuerystringKeys : BasePage.QuerystringKeys
    {            
        public const string Page = "page";
    }
}

public class BasePage : Page
{
    internal class QuerystringKeys
    {
        public const string Username = "username";
        public const string CurrentUser = "currentUser";
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

You can't inherit from structs, ever - and partial types don't inherit from each other anyway. They're just multiple source files combined to create a single type.

I don't know about the details of ASP.NET pages anyway, but the point is that you couldn't have multiple partial types each using the same "base" type but combining with it to form different types. The multiple source files declaring the same partial type are simply combined to form one and only one type.

It seems you're only doing this to share constants though - that strikes me as a poor use of either partial types or inheritance. Just have a CommonQueryKeys static class and reference it appropriately.

Upvotes: 4

Rowland Shaw
Rowland Shaw

Reputation: 38130

I don't believe so.

My understanding on partial classes is that all of the partials that share the same name within an assembly will be attempted to be combined. In your case, it won't know that how you're combining, and will have lots of duplicated names.

You could achieve a similar effect with an abstract class though, although you would need a different name/scope class for each page

Upvotes: 3

Related Questions