Inheritance in ASP.Net Pages - c#

I am new to programming and just now am going through OOPs concepts when I learned about "inheritance" (the process of deriving a new class from an already existing class).
When I opened a new project in asp.net I found this,
public partial class Master_Pages_Email_Template : System.Web.UI.Page
{
which means the class is inherited from page?
When I tried to remove the System.Web.UI.Page some of the code showed errors (ex: IsPostback).
But when in inheritance when I need to access the methods or member variable from a parent class, I have to create a instance isn't it?
But without creating an instance how does this code work?
Sorry if I am wrong..

When an instance of a derived class is created, an "instance" of the base class is created first. That is to say, the derived instance contains everything that would have been in a base instance. In fact, a derived instance is a instance of the base class.
Note that this is not specific to ASP.NET. ASP.NET pages are classes, so this is just normal OO.

If you are new to programming and OOP concepts then OOP has following main pillars.
1. Inheritance
2. encapsulation
3. polymorphism
4. Abstraction
You need to learn all these concepts in order to write any program in Object oriented way.
As far as your questions are concerned. Yes your class is inherited from page. and if you remove System.Web.UI.Page then you can't access method or properties of parent class. Because Inheritance is known as IS A relation.
So if you inherit Class A from Class B then you can access all method or properties of Class A in Class B. but do remember you can access properties or methods of parent class which are not defined as Private (Access Modifiers).
For details about OOP concepts please see. http://msdn.microsoft.com/en-us/library/ms173149.aspx
To understans Access Modifiers

When your class inherits from another class it gets all of the parent class's properties and methods and can use them as if they are its own, also can provide new implementation for these methods. You do not need to create an instance of the class in this case, instantiation is required only when you need to create an object of type class and to use its functionality... I would suggest you learn the basic C# clearly and then going for ASP.Net any such technologies because all of which are based on the base concepts..
PS: this guy got a good list of tutorials on these technologies.. http://www.youtube.com/user/kudvenkat/videos?flow=grid&view=1

A simple code snippet to demonstrate Inheritance and Accessibility.
public class Base
{
private int PrivateProperty { get; set; }
protected int ProtectedProperty { get; set; }
public bool PublicProperty { get; private set; }
}
public class Derived : Base
{
public void A_Method_Which_Need_BaseProperties()
{
if (this.PublicProperty) //Derived can access (only Read) Base PublicProperty
{
this.ProtectedProperty = 1; //Derived can access (Both Read and Write) Base ProtectedProperty
//this.PrivateProperty = 2; //You can't do this. Derived can not access Base PrivateProperty
}
}
}

Related

C# - How to create constructor for inherited class where parent class only has static constructor

For example, say I wanted to create a class that inherits System.Diagnostics.StopWatch, and for this example pretend that System.Diagnostics.Stopwatch.StartNew() is the only public constructor for that class (I know its not, but I'm trying to inherit a different class where that is the case) :
public class Example : System.Diagnostics.Stopwatch
{
public Example()
{
// ... return System.Diagnostics.Stopwatch.StartNew();
}
}
I know there are obvious workarounds, but just wondering if this is possible in C#
There are basically three scenarios where you can't inherit from a class:
The intended parent class is declared as sealed, which prohibits inheriting from it.
The intended parent class doesn't have an accessible constructor.
The intended parent class is a static class.
If you are in one of these 3 scenarios, you will not be able to inherit from that class, plain and simple, don't look for a usable workaround because there isn't.

Is it possible a class to inherit only some(not all) base class members?

Is there a way that a derived class could inherit only a few of all the base class members..in C#?
If such maneuver is possible, please provide some example code.
Is there a way that a derived class could inherit only a few of all the base class members..in C#?
Yes. Make a base class that has one method, one constructor and one destructor. It has three new members, plus the heritable members of its base class. Now derive a class from that. The constructor and destructor will not be inherited; all the other members will. Therefore it is possible to create a derived class which inherits only some of its base class's members.
I suspect that answer is unsatisfying.
If your question is actually "is there a way that a base class can restrict what heritable members are inherited by a derived class?" the answer is no. Derived classes inherit all heritable members of base classes, regardless of their accessibility.
If your question is "is there a way that a derived class can choose which heritable members to inherit from a base class?" the answer is no. Derived classes inherit all heritable members of base classes, regardless of their accessibility.
Further reading, if this topic interests you:
https://ericlippert.com/2011/09/19/inheritance-and-representation/
When you make a type inherit from another, you get everything - both the good and the "bad" bits from the parent type ("bad", in this context, meaning something you didn't want to have).
You can hide something from the parent class in the child class through the new modifier. However, take this advice from years of experience... More often than not this leads to a lot of work being spent on doing workarounds in the way the child class works. You'll spare yourself from a lot of trouble if instead of going this way, you redesign your classes.
If a child type has to clip off functionalities from a parent type, you probably have a design flaw in the parent. Reshape it to have less funcionality. You can have its different features redistributed among different children. A class doesn't always have to be an only child, you know ;)
No, it's not possible. Do you imagine a Cat deriving Animal and the child (the Cat) deciding what's interesting from animals or not? A cat is an animal and this can't be changed.
BTW, interfaces can be used to hide details. For example:
public interface ISome
{
string Text { get; set; }
}
public class A : ISome
{
public string Text { get; set; }
public string Text2 { get; set; }
}
public class B : A
{
}
// This is an upcast. You're reducing the typing of an instance of B
ISome a = new B();
string text2 = a.Text2; // Error, Text2 isn't a property of ISome
string text = a.Text; // OK, Text is a property of ISome

What are the ways to declare a class that cannot be instantiated?

What are the ways to create a non-instantiable class? One way is by declaring it as an abstract class. Is it possible to do it by making the class constructor as private? Is a sealed class, non-instantiable? And, are there any other ways to do it in C#?
Marking a class as abstract or static (they are mutually exclusive) are the only two ways. Marking all constructors as private does not make the class uninstantiateable since the class can still construct itself, and others might be able to do it via reflection.
Only static looks like complete solution here because abstract class still can be instantiated when class instance that inherits from it is instantiated. Consider the scenario :
abstract class A { }
class B : A { }
somewhere in code :
B instance = new B(); // this creates instance of class A as well
P.S.
At first i though that abstract sealed might be solution for this problem as well but it doesn't make much sense to use such a construction so it doesn't even compile :
Error 1 'A': an abstract class cannot be sealed or static D:\Projects\TEST\Testapp\Program.cs 15 27 ITT.Domain
As answered by others abstract and static classes cannot be instantiated however a class with private constructor can be by using a public member function. This is how the singleton pattern works
internal classes are only visible inside of your assembly and therefore cannot be instantiated outside of this assembly.
But as far as i know, you could still create an instance via reflection.
you can disable reflection via ReflectionPermission Class
As mentioned above you could declare it as abstract or add an abstract method.
If you just want to declare a contract, you could use an interface, but that's not a class at all.
sealed means you cannot inherit this class
singleton classes can only be created once per application
singleton
see sealed (C# reference)

Remove dependency on inherited abstract class references

I am trying to setup a scenario where we can create a common set of models for our workgroup and then implement or extend them if/when needed.
I have the following setup:
namespace Workgroup.DomainClasses
{
public abstract class WorkGroupOrder
{
private ICollection<WorkGroupItems> _items;
protected WorkGroupOrder()
{
_items = new List<WorkGroupItems>();
}
protected int OrderId { get; set; }
protected virtual ICollection<WeAccount> Items
{
get { return _items; }
set { _items = value; }
}
}
}
I would prefer that users not use the base WorkGroupOrder so would like to set this up so they are required to implement their own version of the class. If all is good with the base class it would simply be an empty class calling the base constructor but otherwise properties and functionality could be added. The idea for this is that the Workgroup domain is much larger than may be necessary for a single project but we'd like to drive all work from this common model.
using Workgroup.DomainClasses;
namespace Project.DomainClasses
{
public class Order : WorkGroupOrder
{
public string OrderComment { get; set; }
}
}
The issue I'm having is that I'm required to reference both domain models to implement. There is an error below in the Testing() method that I must also reference Workgroup.DomainClasses in order to instantiate the class. I'm not that familiar with abstract classes so is this just the nature of the abstract type? I'd prefer to remove this dependency if possible.
using Project.DomainClasses;
namespace Project.DataLayer
{
public class Testing
{
public void Testing()
{
Order o1 = new Order();
}
}
}
A few questions.
Does this organization make sense or is there a better way to
support my desire of providing a common model that could potentially
be extended?
How would I access the properties of both the base
abstract class and the concrete class? In my Testing() method I am unable
to access `o1.OrderId` for example.
I'd like to remove meta-knowledge of the abstract class from the developer. How would it be best to execute the constructor without explicitly requiring the developer to do so?
Ultimately I'd like to require developers to create their own instance of the class to avoid implementing the base model directly. I'd also like to build in the proper visibility to prevent them from going directly to the Workgroup objects.
It seems like there are a few different issues in play here.
Firstly, using a namespace to try to segregate out base functionality is not a viable option because all derived classes will need access to the namespace of the base class by default (in order to inherit). Any developers extending your base classes will need access to the namespace containing the base classes.
Controlling access to functionality or data is generally best accomplished using access modifiers (eg, public, protected, or private) or public properties with public get{ } and protected set{ } or private set{ } (ie, getters and setters with different acccess levels). If you wish to hide implementation details from the end users, then an interface is the right approach to take (like an API, for example).
Secondly, by marking any class abstract you will automatically deny other developers the ability to instantiate that class directly. They will be forced to create a class derived from the abstract class (aka, a "concrete" class) in order to use the abstract base class's methods and properties.
Third, the reason you couldn't access property o1.OrderId in your test code is because that property has an access modifier of protected. This means that only the base class and its derived classes can internally access this property. To expose it to the end user, it must be marked public.
Unfortunately, I do not really understand what you mean with "setup a scenario where we can create a common set of models for our workgroup and then implement or extend them if/when needed". What is a workgroup in your context? And why should (all) other classes derive from it?
Anyway, you cannot use o1.OrderID because this property is protected which means it is only visible within the scope of WorkOrderGroup and subclasses that derive from it. Make this property public and you can access it everywhere.
Furthermore, and please take no offence, but it seams that you somewhat struggle with the object-oriented concepts of encapsulation and inheritance. I would advise you to have a look at these concepts (you can e.g. start here) and get a good understanding what they do and how to use them when implementing functionality. With the current information, I would not advise you to structure your code like you explained in your question.
Finally, some general hints on practices in object-oriented languages:
Favor composition over inheritance: this means that you should extend existing classes by encapsulating them instead of inheriting from them. In most cases this is more flexible.
Take a look at the SOLID princples: they provide really good instructions that you should consider on every class you write.
Take a look at Design Principles and maybe Domain-Driven-Design: there is a lot of guidance on the internet out there with a lot of examples. With every examples you get a better feeling how to approach new problems and how to model them in OOD.
I hope this answer guides you in the correct direction.

Decreasing the visibility of base class properties

I had created a base class that has many public properties and were been used perfectly. Now i want to use this class to derive other class , but i do'nt want some of its properties to be exposed outside the derived class that inherits it. Is there any way that the properties of base class that are public cannot be exposed outside its derived class.(The properties that are to be hidden are public because they are used in other classes that inherits it).Any help will be highly appericiated.
You want to make them protected.
From MSDN:
A protected member is accessible within its class and by derived class instances.
I agree with cadrell0 about marking them protected, but just in case you are looking for a solution where the properties are actually public, but hidden to users of a certain derived class, you can use an explicit interface
interface IHaveMethodsYouCanHide { void Foo(); }
class Base : IHaveMethodsYouCanHide { public void Foo() {} }
class NonHidingDerived : Base { }
class HidingDerived : Base, IHaveMethodsYouCanHide
{
void IHaveMethodsYouCanHide.Foo() {}
}
With this code, identifers of type HidingDerived will not allow calls to Foo (unless first cast to IHaveMethodsYouCanHide).
What you're asking for is simply not possible. If type B inherits from type A then it "is-a" type A. B has at least the same accessible contract that type A had. There is no way to hide a public member of A without fundamentally violating this contract.
If you find yourself in a scenario where you want to use A but only expose a subset of the properties then inheritance is not the right solution: containment is the proper solution.
public class B {
private A m_wrapped;
// Expose only the properties you want to expose here
}

Categories