Inconsistent Accessability: Base Class is less accessible than class - c#

I've got the code below and I'm trying to do some inheritance exercises but when I try to run this code it gives me an error:
Inconsistent Accessability: Base Class is less accessible than class
The code:
class Program
{
static void Main()
{
FoodProducts Test = new FoodProducts();
Test.Limit();
}
}
public class FoodProducts : Products
{
public void FoodProduct()
{
Console.WriteLine("This is food product");
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
Would someone be able to help me?

What line is the error on, and what is the specific error text? Also, where is the definition of Products?
You are probably getting CS0060: "Inconsistent accessibility: base class 'class1' is less accessible than class 'class2'" Thus, I'm assuming your Products class is not marked as public.
This problem happens when a base class is marked as something other than public (internal, for example), but then you try to make a public derived class.

Just for future reference for someone thick like me, I got this in the following situation and couldn't figure out what was going wrong:
public class Foo : Base<Bar> {} <-- Inconsistent accessibility
public class Base<T> {}
It took me a while to work out that the culprit was here:
internal class Bar {}

Lots of answers here suggest to change your base class into public too. In a sense they are correct, but then they miss an equally valid alternative, which is to change your derived class to internal (to match what the base class's accessibility).
So, the real (yet short) answer is to let your base class and derived class to have same accessibility.
For those who wonder why, the long answer is: when a public derived class attempts to inherit an internal or private base class, it would argurably (more on this later) become semantically unclear whether the sub-class would also want to expose those public methods in the internal/private base class. Eric Lippert gave an detailed explanation in his blog post: Why is deriving a public class from an internal class illegal?, quoted below (with minor edit):
On the one hand, it is a public method of a base class, and so it seems like it should be accessible (to the derived class too). On the other hand, the fact that Base is internal is evidence that its internal method is supposed to be inaccessible outside the assembly. A basic design principle of C# is that when the intention is unclear, the compiler brings this fact to your attention by failing.
PS: That being said, one may argue that, the compiler could possibly just stick with "one of those 2 hands" and it would still be deterministic. So why was the design decision NOT chosen on one specific way? For such a follow-up question, the answer is, it all boils down to design philosophy that (again, quoted from Eric's blog post):
this rule of the language encourages you to use inheritance relationships to model the business domain semantics rather than as a mechanism for code reuse.
So that was the choice C# already made.
Lastly, for the sake of completeness, it is worth to mention that, the design philosophy above is not necessarily the universal and only way to use inheritance. (Heck, some other languages do not even have the public/internal concept in the first place and they are still successful). Personally I see nothing wrong if we would also want to use inheritance mechanism for code reuse. But C# already chose to only use inheritance for business domain semantics. So, it is what it is.

Probably the class Products is not public. Add public to the Products class definition.
If you have something like:
class Products {
...
}
The C# compiler interprets the Products class as internal.

Add the public directive to the class you are trying to inherit from.

public class Products
Make you class public(as shown above) in order for it to be inherited or accessible.

You can also add this before the definition of the namespace in your base class (right after the last "using ..." line):
[assembly: InternalsVisibleTo("<name of the assembly of the caller class>")]

That happens when, for example, the base class is private, but the derived class is public. A contradiction, so to speak.

this means if you wish a public child class, the parent class must be public also.

One of the probable reason for this issue may be , you have more than one main class , Make sure you have only one main class.

Related

Abstract class cannot be sealed in c#?

I read somewhere
"Abstract and Sealed modifiers are equivalent to a class which is static"
I also found that
"When you declare a static class, internally the compiler marks the class abstract and sealed, and creates a private constructor in the IL code"
so, I decided to do this:
static class A
{
public static void test()
{
Console.WriteLine("test");
}
}
Now, the class "A" cannot be inherited nor instantiated.
So, let us write a class B using abstract to prevent instantiation and using sealed to prevent inheritance.
But, this approach fails.
which should be equivalent to
public abstract sealed class B
{
private B()
{
}
public void test()
{
Console.WriteLine("test");
}
}
But I recieve an error stating "error CS0418:B': an abstract class cannot be sealed or static"` . Any ideas why this is not possible ?
Thanks in advance for your answers.
Having checked the IL of the System.Directory class (which is static), it is declared in IL as:
.class public auto ansi abstract sealed beforefieldinit System.IO.Directory
extends System.Object
{
...
Further, this article (http://msdn.microsoft.com/en-us/library/ms229038.aspx) suggests that the CLR handles static classes as abstract sealed classes to support languages that do not support directly delcaring static classes (eg C++).
Thus in conclusion, static classes in C# are syntactic sugar for sealed abstract classes with private constructors. I for one am glad of that as "static" is a lot easier to write and a lot easier to get right.
By definition a sealed class enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.
Abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
(Source: http://msdn.microsoft.com/en-us/library/ms173150.aspx)
This would imply that any class marked abstract would not be able to be sealed, since you wouldn't be able to derive it anywhere.
The code you mentioned doesn't make any sense.
All answers somehow take the technical point of view. Such as: the class can't be "must inherit" and "can't inherit" at the same time. But I think that is not the main reason, as clearly, the "static" is just that.
I think David Amo's answer has touched the real answer a bit, by stating: "it is a lot easier to get right".
I am convinced that Anders Hejlsberg's idea when designing C# was to eliminate ambiguity and thus decrease a chance for error. That's why "virtual" goes with "override" (override has to be explicit, not implicit as in Java). And in this case, "abstract"+"sealed" would be the same as "static". Two ways of defining the same principle. This is:
- more error prone (imagine you have abstract somewhere and put sealed there accidently without noticing, onw compiler prevents that)
- more difficult to work with (imagine you want to search for all static classes in your project)
So my point is, this entire design leads the developers the right way of doing things.

Object oriented design: when to make an abstract class

Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.

Abstract Method in Non Abstract Class

I want to know the reason behind the design of restricting Abstract Methods in Non Abstract Class (in C#).
I understand that the class instance won't have the definition and thus they wont be callable, but when static methods are defined,they are excluded from the instance too. Why abstract methods are not handled that way, any specific reason for the same?
They could be allowed in concrete class and the deriving class can be forced to implement methods, basically that is what, is done in case of abstract methods in an abstract class.
First, I think that what you're asking doesn't logically make sense. If you have an abstract method, it basically means that the method is unfinished (as #ChrisSinclair pointed out). But that also means the whole class is unfinished, so it also has to be abstract.
Or another way to put it: if you had an abstract method on a class that wasn't abstract, that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same.
Now, I'll try to be more concrete by using an example: imagine the following code:
Animal[] zoo = new Animal[] { new Monkey(), new Fish(), new Animal() };
foreach (Animal animal in zoo)
animal.MakeSound();
Here, Animal is the non-abstract base class (which is why I can put it directly into the array), Monkey and Fish are derived from Animal and MakeSound() is the abstract method. What should this code do? You didn't state that clearly, but I can imagine few options:
You can't call MakeSound() on a variable typed as Animal, you can call it only using a variable typed as one of the derived classes, so this is a compile error.
This is not a good solution, because the whole point of abstract is to be able to treat instances of derived classes as the base class, and still get behaviour that's specific to the derived class. If you want this, just put a normal (no abstract, virtual or override) method into each derived class and don't do anything with the base class.
You can't call MakeSound() on an object whose runtime type is actually Animal, so this is a runtime error (an exception).
This is also not a good solution. C# is a statically typed language and so it tries to catch errors like “you can't call this method” at compile time (with obvious exceptions like reflection and dynamic), so making this into a runtime error wouldn't fit with the rest of the language. Besides, you can do this easily by creating a virtual method in the base class that throws an exception.
To sum up, you want something that doesn't make much sense, and smells of bad design (a base class that behaves differently than its derived classes) and can be worked around quite easily. These are all signs of a feature that should not be implemented.
So, you want to allow
class C { abstract void M(); }
to compile. Suppose it did. What do you then want to happen when someone does
new C().M();
? You want an execution-time error? Well, in general C# prefers compile-time errors to execution-time errors. If you don't like that philosophy, there are other languages available...
I think you've answered your own question, an abstract method isn't defined initially. Therefore the class cannot be instanciated. You're saying it should ignore it, but by definition when adding an abstract method you're saying "every class created from this must implement this {abstract method}" hence the class where you define the abstract class must also be abstract because the abstract method is still undefined at that point.
The abstract class may contain abstract member. There is the only method declaration if any method has an abstract keyword we can't implement in the same class. So the abstract class is incompleted. That is why the object is not created for an abstract class.
Non-abstract class can't contain abstract member.
Example:
namespace InterviewPreparation
{
public abstract class baseclass
{
public abstract void method1(); //abstract method
public abstract void method2(); //abstract method
public void method3() { } //Non- abstract method----->It is necessary to implement here.
}
class childclass : baseclass
{
public override void method1() { }
public override void method2() { }
}
public class Program //Non Abstract Class
{
public static void Main()
{
baseclass b = new childclass(); //create instance
b.method1();
b.method2();
b.method3();
}
}
}
You can achieve what you want using "virtual" methods but using virtual methods can lead to more runtime business logic errors as a developer is not "forced" to implement the logic in the child class.
I think there's a valid point here. An abstract method is the perfect solution as it would "enforce" the requirement of defining the method body in children.
I have come across many many situations where the parent class had to (or it would be more efficient to) implement some logic but "Only" children could implement rest of the logic"
So if the opportunity was there I would happily mix abstract methods with complete methods.
#AakashM, I appreciate C# prefers compile time errors. So do I. And so does anybody. This is about thinking out-of-the-box.
And supporting this will not affect that.
Let's think out of the box here, rather than saying "hurrah" to big boy decisions.
C# compiler can detect and deny someone of using an abstract class directly because it uses the "abstract" keyword.
C# also knows to force any child class to implement any abstract methods. How? because of the use of the "abstract" keyword.
This is pretty simple to understand to anyone who has studied the internals of a programming language.
So, why can't C# detect an "abstract" keyword next to a method in a normal class and handle it at the COMPILE TIME.
The reason is it takes "reworking" and the effort is not worth supporting the small demand.
Specially in an industry that lacks people who think out of the boxes that big boys have given them.
It's still not clear why you would want that, but an alternative approach could be to force derived classes to provide a delegate instance. Something like this
class MyConcreteClass
{
readonly Func<int, DateTime, string> methodImpl;
// constructor requires a delegate instance
public MyConcreteClass(Func<int, DateTime, string> methodImpl)
{
if (methodImpl == null)
throw new ArgumentNullException();
this.methodImpl = methodImpl;
}
...
}
(The signature string MethodImpl(int, DateTime) is just an example, of course.)
Otherwise, I can recommend the other answers to explain why your wish probably isn't something which would make the world better.
So the answers above are correct: having abstract methods makes the class inherently abstract. If you cannot instance part of a class, then you cannot instance the class itself. However, the answers above didn't really discuss your options here.
First, this is mainly an issue for public static methods. If the methods aren't intended to be public, then you could have protected non-abstract methods, which are allowed in an abstract class declaration. So, you could just move these static methods to a separate static class without much issue.
As an alternative, you could keep those methods in the class, but then instead of having abstract methods, declare an interface. Essentially, you have a multiple-inheritance problem as you want the derived class to inherit from two conceptually different objects: a non-abstract parent with public static members, and an abstract parent with abstract methods. Unlike some other frameworks, C# does permit multiple inheritance. Instead, C# offers a formal interface declaration that is intended to fill this purpose. Moreover, the whole point of abstract methods, really, is just to impose a certain conceptual interface.
I have a scenario very similar to what the OP is trying to achieve. In my case the method that I want to make abstract would be a protected method and would only be known to the base class. So the "new C().M();" does not apply because the method in question is not public. I want to be able to instantiate and call public methods on the base class (therefore it needs to be non-abstract), but I need these public methods to call a protected implementation of the protected method in the child class and have no default implementation in the parent. In a manner of speaking, I need to force descendants to override the method. I don't know what the child class is at compile time due to dependency injection.
My solution was to follow the rules and use a concrete base class and a virtual protected method. For the default implementation, though, I throw a NotImplementedException with the error "The implementation for method name must be provided in the implementation of the child class."
protected virtual void MyProtectedMethod()
{
throw new NotImplementedException("The implementation for MyProtectedMethod must be provided in the implementation of the child class.");
}
In this way a default implementation can never be used and implementers of descendant implementations will quickly see that they missed an important step.

Why can't my public class extend an internal class?

I really don't get it.
If the base class is abstract and only intended to be used to provide common functionality to public subclasses defined in the assembly, why shouldn't it be declared internal?
I don't want the abstract class to be visible to code outside the assembly. I don't want external code to know about it.
UPDATE: This question was the subject of my blog on November 13th of 2012. See it for some more thoughts on this issue. Thanks for the great question!
You're right; it doesn't have to be that way. Other OO languages allow "private inheritance", whereby the fact that D inherits from B can only be taken advantage of by code that has the ability to see B.
This was a design decision of the original C# designers. Unfortunately I am away from my desk right now - I'm taking a couple of days off for the long weekend - so I don't have the language design notes from 1999 in front of me. If I think of it when I get back I'll browse them and see if there is a justification for this decision.
My personal opinion is that inheritance should be used to represent "is a kind of" relationships; that is, inheritance should represent the semantics of the domain being modelled in the language. I try to avoid situations where inheritance is used as a code sharing mechanism. As others have mentioned, it's probably best to prefer composition to inheritance if what you want to represent is "this class shares implementation mechanisms with other classes".
By inheriting from a class, you expose the functionality of the base class through your child.
Since the child class has higher visibility than its parent, you would be exposing members that would otherwise be protected.
You can't violate the protection level of the parent class by implementing a child with higher visibility.
If the base class is really meant to be used by public child classes, then you need to make the parent public as well.
The other option is to keep your "parent" internal, make it non-abstract, and use it to compose your child classes, and use an Interface to force classes to implement the functionality:
public interface ISomething
{
void HelloWorld();
}
internal class OldParent : ISomething
{
public void HelloWorld(){ Console.WriteLine("Hello World!"); }
}
public class OldChild : ISomething
{
OldParent _oldParent = new OldParent();
public void HelloWorld() { _oldParent.HelloWorld(); }
}
I think the closest thing you can do is prevent other assemblies creating the abstract class by making its constructor internal, to quote from MSDN:
An internal constructor prevents the abstract class from being used as the base class of types that are not in the same assembly as the abstract class.
You can then try adding an EditorBrowsableAttribute to the class to try and hide it from IntelliSense (though, I've had mixed results using it to be honest) or put the base class in a nested namespace, such as MyLibrary.Internals to seperate it from the rest of your classes.
I think you're mixing concerns here, and C# is to blame, actually (and Java before it).
Inheritance should serve as a categorization mechanism, whereas it's often used for code reuse.
For code reuse it's always been known that composition beats inheritance. The problem with C# is that it gives us such an easy way to inherit:
class MyClass : MyReusedClass { }
But in order to compose, we need to do it by ourselves:
class MyClass {
MyReusedClass _reused;
// need to expose all the methods from MyReusedClass and delegate to _reused
}
What's missing is a construct like a trait (pdf), which will bring composition to the same usability level as inheritance.
There's research about traits in C# (pdf), and it would look something like this:
class MyClass {
uses { MyTrait; }
}
Although I'd like to see another model (that of Perl 6 roles).
UPDATE:
As a side note, the Oxygene language has a feature that lets you delegate all members of an interface to a member property that implements that interface:
type
MyClass = class(IReusable)
private
property Reused : IReusable := new MyReusedClass(); readonly;
implements public IReusable;
end;
Here, all interface members of IReusable will be exposed through MyClass and they'll all delegate to the Reused property. There are some problems with this approach, though.
ANOTHER UPDATE:
I've begun implementing this automatic composition concept in C#: take a look at NRoles.
I think this would violate the Liskov Substitution Principle.
In cases like this, I have used internal classes and prefer composition over inheritance. Is there anything about your design that prohibits containing all such functionality in your internal class, and then have your public classes contain an instance of this internal class?

How to handle a class you want to extend which is sealed in the .NET library?

I was reading somewhere about how to handle the issue of wanting to extend a sealed class in the .NET Framework library.
This is often a common and useful task to do, so it got me thinking, in this case, what solutions are there? I believe there was a "method" demonstrated to extend a sealed class in the article I read, but I cannot remember now (it wasn't extension methods).
Is there any other way?
Thanks
There is 'fake' inheritance. That is, you implement the base class and any interfaces the other class implements:
// Given
sealed class SealedClass : BaseClass, IDoSomething { }
// Create
class MyNewClass : BaseClass, IDoSomething { }
You then have a private member, I usually call it _backing, thus:
class MyNewClass : BaseClass, IDoSomething
{
SealedClass _backing = new SealedClass();
}
This obviously won't work for methods with signatures such as:
void NoRefactoringPlease(SealedClass parameter) { }
If the class you want to extend inherits from ContextBoundObject at some point, take a look at this article. The first half is COM, the second .Net. It explains how you can proxy methods.
Other than that, I can't think of anything.
Extension methods is one way, the alternative being the Adapter Pattern. Whereby you write a class that delegates some calls to the sealed one you want to extend, and adds others. It also means that you can adapt the interface completely into something that your app would find more appropriate.
this method may have already been mentioned above by it's formal name, but i don't know it's formal name, so here it is. This example "extends" the TextBox class (example in VB). I believe an advantage of this method is that you do not need to explicitly code or expose built-in members. Hope this is relevant:
VB Class Module "MyTextBox":
public Base as TextBox, CustomProperty as Integer
Private Sub Init(newTextBox as TextBox)
Set Base = newTextBox
End Sub
public Property Get CustomProperty2() As String
CustomProperty2 = "Something special"
End Property
To call the code, you might say:
Dim MyBox as New MyTextBox
MyBox.Init MyForm.TextBox3
from here you have access to all built-in members, plus your custom members.
Debug.Print MyBox.Base.Text
MyBox.CustomProperty = 44
For extra polish, you can make Base the default property of the class, and then you can leave out "Base" when you call properties of the Base class. You call Base members like this:
Debug.Print MyBox().Text
MyBox().Text = "Hello World"
VBA Demo
Maybe use the Decorator pattern?
Other than extension methods, this is the only sensible technique I can think of.
No, you can't extend a sealed class in any legitimate way.
TypeMock allows you to mock sealed classes, but I doubt that they'd encourage you to use the same technique for production code.
If a type has been sealed, that means the class designer has not designed it for inheritance. Using it for inheritance at that point may well cause you lots of pain, either now or when the implementation is changed at a later date.
Prefer composition to inheritance - it's a lot more robust, in my experience. See item 16 in "Effective Java (2nd edition)" for more on this.
The only way I know to "extend" a sealed class without extension methods is by wrapping it. For example:
class SuperString
{
private String _innerString;
public SuperString(String innerString)
{
_innerString = innerString;
}
public int ToInt()
{
return int.Parse(_innerString);
}
}
You'd need to expose all of the same methods/properties as the string class.
Some frameworks allow you to extend existing objects. In WPF, see Dependency Properties. For Windows Forms, see IExtenderProvider.
How about extension methods? You can "add" additional methods that way, without having to deal with the inheritance restriction.

Categories