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.
I have create the project and put the Interface and class in the same folder. I'm using Unity container to resolve the interface for object of the class. Now I have another assembly that want to access the assembly about. I don't want anyone to access my class directly. So if it is possible to register type of the internal class it will good for me. Any idea?
You could try around with Friend assemblies, but I think it will just cause you problems in the long run.
Instead I would consider two other options.
Option A: Use a factory.
Suggested here: Unity 1.2 Dependency injection of internal types.
public class FactoryClass
{
public IMyInterface CreateInstance()
{
return new MyInternalClass();
}
}
internal class MyInternalClass : IMyInterface
{
}
Also consider using an public class with an internal constructor, which would force an internal class to create the instance. More information here: What's the difference between a public constructor in an internal class and an internal constructor?.
public class MyAlmostInternalClass // in lack of better name
{
internal MyAlmostInternalClass() {}
}
Option B: Reconsider your class completely
Why does it need to be internal? Shouldn't the other assembly use the interface anyway? Make it sealed if you don't want anyone the derive from it and don't have any public properties other than the one from the interface it implements. Then there's really no reason to use the class over the interface.
I would like to add some additional methods to System.Windows.Input.Keyboard.I have tried to create a partial class like this;
namespace System.Windows.Input
{
public static partial class Keyboard
{
//some code...
}
}
However when I try this Resharper informs me that this is not a partial file and when I try to use it I get an ambiguous reference error although both Keyboards are shown as being in the same namespace. Is what I'm trying to do even possible and if not, why not?
No, it's not possible. Keyboard is a static class.
Static classes cannot be instantiated and they cannot be extended.
You can always write your own (static) class and put your methods in there.
You shouldn't use the same namespace as Keyboard, the class should be only static, you can name the class whatever you want "KeyboardExtensions" for exemple
See this for extension methods https://msdn.microsoft.com/en-us/library/bb383977.aspx
What you are trying to do is not possible because the Keyboard class is not partial to begin with.
The ambiguous reference is caused by the fact that you're creating a class that already exists in the same namespace so the compiler doesn't know which one to use.
You cannot create a static class that inherits from another static class as suggested by #harmoniemand. Static classes can only inherit from Object.
And you cannot create extension methods on a static class as #Hamza_L seems to be suggesting because you can't use static types as parameters in extension methods.
with a look at the manual, you could see that the System.Windows.Input.Keyboard is not defined as partial (look here) so you are not able to extend it this way.
The better way to do it, is to write an inherited class.
namespace MyApplication.Wrapper
{
public static class MyKeyboard : System.Windows.Input.Keyboard
{
//some code...
}
}
I am new to C# programming. I understand that it is necessary to modify the class as abstract if it contains any abstract methods, and its implementation must be provided in any of the child classes in class hierarchy.
But my question is whether can we have an abstract class without any abstract methods(so it is not necessary for it to be a base class), and if it is so, then what are the significance of the same. Please help in this regard. :)
Yes you can have an abstract base class without any abstract methods. The benefit is that you cannot create an instance of this class.
There is a consideration to replace that abstract class with an interface. The difference is that the interface may not contain any implementation, but in the abstract class you can provide some implementation for methods that any inheritor may use.
You cann't create instances of the abstract class, and if you are not use this class as base - it is useless (only possible for some tricky goals using reflection)
Yes, it can be used without having an implementing subclass. Basically you have three "ways" of defining and calling methods here:
static: Methods that can be called directly on the abstract class, because they do not require an instance at all.
abstract: Methods that must be implemented in a sub-class (note that the existance of one of these does not stop you from using any existing static methods directly!)
"Regular": Normal methods, implemented directly in the abstract class, and which can be called via an instance of a sub-class. Note that you can only call them via sub-classes, since you can only have instances of a subclass (not the abstract class itself). Such a sub-class must also by definition implement any abstract method(s) in the abstract class (otherwise you`ll get a compile time error).
The following simple console app gives a nice, concrete (no pun intended) example:
using System;
namespace ConsoleStuff
{
public abstract class MyAbstractClass
{
public abstract void DoSomethingAbs();
public void DoSomethingElse()
{
Console.WriteLine("Do something general...");
}
public static void TakeABreak()
{
Console.WriteLine("Take a break");
}
}
class MyImplementation : MyAbstractClass
{
public override void DoSomethingAbs()
{
Console.WriteLine("Do something Specific...");
}
}
class Program
{
static void Main(string[] args)
{
// Static method; no instance required
MyAbstractClass.TakeABreak();
var inst = new MyImplementation();
inst.DoSomethingAbs(); // Required implementation in subclass
inst.DoSomethingElse(); // Use method from the Abstract directly
Console.ReadKey();
}
}
}
Neither is instantiable. What are the differences, and in what situations might you use one or the other?
static indicates the class can only have static members and you cannot create an instance of it. This is used for stateless functionality (for example a type that just defines extension methods, or utility methods). You can also declare a member static on a non-static class. This allows you to attach functionality to a type without having to instantiate it.
Here's more detail on using static members and classes.
abstracts define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. Think of them as, I suppose, a blue print and a contract. This is a core concept for OOP.
Here's more detail on using abstracts.
Here is a short summary:
A static class can only contain static members (it is just a container for methods that do not logically belong to an instance of any standard class)
An abstract class can contain all usual kinds of members (static, abstract and also instance)
The key difference is that you can inherit from an abstract class, but you cannot inherit from a static class. Technically speaking, the .NET runtime doesn't have any notion of static classes, so the C# compiler compiles them as classes that are both abstract and sealed (meaning that you cannot inherit from them).
So, static classes are abstract classes that are also sealed (although this is not the usual way to look at the problem if you are C# programmer) and contain only static members (which is enforced by the C# compiler).
An abstract class is intended to be used as a base of a class inheritance hierarchy. A static class cannot be the base of a class inheritance hierarchy.
A static class is intended for singleton state or stateless functionality. An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses. Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.
The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated. Beyond that, they are completely different animals with completely different use cases.
The CLR has no notion of static classes, it is specific to C#. The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed. That prevents any language from instantiating such a class. This is what it looks like when you run Ildasm:
.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
extends [mscorlib]System.Object
{
}
Making it sealed is very much the point of a static class, it is used as a container for static methods and fields. Which makes them act like global variables and functions like you have in languages like C or Pascal.
An abstract class is very much the opposite, it is designed to be derived from. A abstract class that has all of its member abstract acts like an interface. C# has a keyword for that, making static class and interface the exact opposites.
Abstract classes get instantiated indirectly via derived classes. They provide common behaviour and instance state, but signal that more is required and must be provided by derived concrete classes. For example, Transform might be an abstract class: it declares a common Apply(Shape) method, but no implementation of that method. Concrete derived classes like Rotation or Translation will implement that method, and those classes can be instantiated.
Static classes cannot be instantiated, and any state is at the class level rather than the instance level. They are typically used to define utility methods where there is no state associated with the methods. Transform couldn't be a static class, because the concrete derived classes need per-instance state (e.g. Rotation needs a per-instance Angle, because different Rotation transforms could be by different angles).
Abstract classes are intended to be used as base classes; they cannot have direct instances. Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.
Example: consider you have a complex application, where users may log-in to. Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it. One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:
abstract class Authenticator {
protected Dictionary<string,User> userCache;
...
public User LoadUser(string name) {
User user;
if( userCache.TryGet(name, out user) ) return user;
else {
user = LoadFromStore(name);
userCache.Add(name, user);
return user;
}
}
protected abstract User LoadFromStore(string name);
}
Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.
Static class are a different matter alltogether. They are essentially a place to keep your utility functions:
static class StrUtil {
public static string TrimWhitespace(string str) {
...
}
}
Think of them as some kind of special namespace, which can only contain static members. Basically, a place to put functions.
Abstract Class (Base class):
Enables other classes to inherit from this class (one class acquires the properties (methods and fields) of another) , but forbids to instantiate i.e we cannot have objects of this class.
http://csharp.net-tutorials.com/classes/abstract-classes
Static Class:
This class cannot be instantiated. Also this class cannot be inherited. To access methods of this class, you can directly use classname.method.
https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx
Abstract class main purpose is to define one or more abstract method(s).
Any class extending Abstract class will implement the abstract method or else its also need to be declared as "Abstract".
But, its also possible to declare a class as "Abstract" without implementing any abstract method(s) in it. See the sample below.
public abstract class AbstractTest {
public void abcd(){}
public static void main(String[] args) {
System.out.print("hi...");
}
}
Only inner class can be declared as "Static", see the code below.
Upper/encapsulating class can't be declared as "Static".
It can be accessed by using Upper/encapsulating class variable.Static-inner-classname i.e same as any static method invocation using class name.
public class StaticTest {
public static void main(String ag[]){
System.out.println("hello...1");
StaticTest.StaticTest2.meth2();
}
public static class StaticTest2 {
public static void meth2(){
System.out.print("hello...2");
}
}
}
Main difference between the two is extensibility.
CLR marks all 'static' classes as 'abstract & sealed' behind the scene (i.e., they cannot be inherited hence cannot be extended) and .NET Framework CLR loads them automatically when containing program or namespace is loaded. This gives performance gain on runtime.
Philosophy behind 'abstract' classes is capitalizing all common features of all extended classes in one place.
Hope it helps.