Class vs. Interface accessibility question

  • Thread starter Hans De Schrijver
  • Start date
H

Hans De Schrijver

I'm pretty new to C# development, so here's a newby question regarding
accessibility:

Scenario:
class1 contains some basic properies and methods
class2 inherits from class1 and adds some properties and methods
class3 inherits from class2 and adds some properties and methods

class1 and class2 are logically abstract classes that the consumer of my
class library should not be able to instantiate.
class3 is the only class from which the consumer of my class library should
be able to create instances.


I was planning on creating class1 and class2 as abstract classes, but it
seems that you cannot put any code in abstract classes, in other words, the
implementing class always has to provide the actual implementation.
I read somewhere that Interfaces might be the answer, but I'm somewhat
confused because Interfaces don't seem to contain code for methods either...
they just provide a contract that must be implemented by the class that
implements the interface. Moreover, I believe interfaces are typically
contracts that can be applied to unrelated classes, whereas in my case,
class1 and class 2 really only apply to class3 and not to any other class.
So both abstract classes and interfaces don't seem to allow me to provide
actual code implementation that I can inherit.

Can someone please shed some light on this and maybe make a recommendation
about how I should go about it? I'd greatly appreciate it!

-- Hans De Schrijver
 
D

David Browne

Hans De Schrijver said:
I'm pretty new to C# development, so here's a newby question regarding
accessibility:

Scenario:
class1 contains some basic properies and methods
class2 inherits from class1 and adds some properties and methods
class3 inherits from class2 and adds some properties and methods

class1 and class2 are logically abstract classes that the consumer of my
class library should not be able to instantiate.
class3 is the only class from which the consumer of my class library should
be able to create instances.


I was planning on creating class1 and class2 as abstract classes, but it
seems that you cannot put any code in abstract classes, in other words, the
implementing class always has to provide the actual implementation.

Not true. You can have non-abstract members of an abstract class. EG


abstract class Class1
{
protected abstract void flarg();
void useFlarg()
{
flarg();
}
}
abstract class Class2 : Class1
{
protected abstract void otherFlarg();
}
class Class3 : Class2
{
protected override void flarg()
{
;
}
protected override void otherFlarg()
{
;
}
}

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top