How to extend System.Windows.Input.Keyboard class - c#

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...
}
}

Related

Is it possible to do static partial classes?

I want to take a class I have and split it up into several little classes so it becomes easier to maintain and read. But this class that I try to split using partial is a static class.
I saw in an example on Stackoverflow that this was possible to do but when I do it, it keeps telling me that I cannot derive from a static class as static classes must derive from object.
So I have this setup:
public static class Facade
{
// A few general methods that other partial facades will use
}
public static partial class MachineFacade : Facade
{
// Methods that are specifically for Machine Queries in our Database
}
Any pointers? I want the Facade class to be static so that I don't have to initialize it before use.
Keep naming and modifiers consistent across files:
public static partial class Facade
{
// A few general methods that other partial facades will use
}
public static partial class Facade
{
// Methods that are specifically for Machine Queries in our Database
}
The problem is not that the class is a partial class. The problem is that you try to derive a static class from another one. There is no point in deriving a static class because you could not make use Polymorphism and other reasons for inheritance.
If you want to define a partial class, create the class with the same name and access modifier.
you do not need to override anything, just give them the same name:
public static partial class Facade
{
// this is the 1st part/file
}
public static partial class Facade
{
// this is the 2nd part/file
}
You can not inherit a static class.
Static classes are sealed and therefore cannot be inherited. They
cannot inherit from any class except Object.
C# doesn't support inheritance from a static class.
You have to choose between your classes being static:
public static class Facade
{
// A few general methods that other partial facades will use
}
public static partial class MachineFacade
{
// Methods that are specifically for Machine Queries in our Database
}
...or whether you wish MachineFacade to derive from Facade:
public class Facade
{
// A few general methods that other partial facades will use
}
public partial class MachineFacade : Facade
{
// Methods that are specifically for Machine Queries in our Database
}
Although I am too late for the party...
According to your problem description, I think your goals are:
Want a static method group.
Want a sub-group of it to be specialized for certain domain.
In this case, I would suggest using nested classes:
public static class Facade
{
// some methods
public static class Machine
{
// some other methods
}
}
Pros:
Methods are static. You can use them directly without initialize any instances.
The nested class names are used like namespaces. Readers of your code knows clearly that Facade.Machine methods are more specific than Facade ones and their target domain.
You can make methods with the same signature in different class level doing different things to mimic method overriding.
Cons:
There is no way to forbids users calling Facade.Machine methods when they should not.
No inheritance. Facade.Machine does not automatically have methods from Facade.

C# Class Definitions - Which Keyword?

I'm not entirely sure about this. Is it 'static'?
The keyword you're looking for is partial.
https://msdn.microsoft.com/en-us/library/wa80x488.aspx
Yes partial is needed, but you also need abstract on the methods and the classes or it still won't compile because non-abstract methods must declare a body.
No It's not static. You need Partial Class. Also You need to provide body to your functions.
It is possible to split the definition of a class or a struct, an
interface or a method over two or more source files. Each source file
contains a section of the type or method definition, and all parts are
combined when the application is compiled.
To split a class definition, use the partial keyword modifier.
See Below example:
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}

Foward Declarations in C#

I really like declaring all of my methods at the start of a class and would like to do so with forward declarations and then implement them further down. Is this possible in C#?
Ex:
private void Test();
private void Test()
{
}
Yes you can do this. Or you can kinda sorta do this. But for each of these possible "Solutions", if it is for cosmetic reasons only don't use these constructs.
One trick is to use a partial class with partial methods.
partial class A
{
partial void OnSomethingHappened(string s);
}
// This part can be in a separate file.
partial class A
{
/* Comment out this method and the program
will still compile.*/
partial void OnSomethingHappened(string s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
As highlighted in the referenced documentation, its uses are limited:
A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time.
The following conditions apply to partial methods:
Signatures in both parts of the partial type must match.
The method must return void.
No access modifiers are allowed. Partial methods are implicitly private.
As pointed out in #Serv and #StanimirYakimov answers, another "kinda sorta" construct that can be used is the declaration of an interface or pure abstract class, very similar to how you would declare one in c++:
public interface IA
{
int GetTheOneAndOnlyNumber();
}
public abstract class AA
{
protected abstract void OnSomethingHappened(string s);
}
public class A : AA, IA
{
public int GetTheOneAndOnlyNumber()
{
return 42;
}
protected override void OnSomethingHappened(string s)
{
Console.WriteLine(s);
}
}
When switching from a language we know well to a new language, there are always specific idioms and constructs that we will miss. This does not mean that it is wise to try to emulate them with non-idiomatic constructs in the new language.
If you would like to have a condensed view of the structure of your code in Visual Studio, there are several standard ways of doing that, such as the Object Browser and Class View.
And if you search and look around, you will find other available tools that can help you with getting a quick overview of the structure of your code.
You can do it using interfaces
Just define which methods your class will use by inheriting from an interface.
See this interface as a mixture of forward declarations and a contract. Classes inherting from an interface must implement all of its members.
public interface iSomeClass
{
void MyMethod1();
bool MyBoolMethod();
}
public class MyClass : iSomeClass
{
public void MyMethod1()
{
//...
}
public bool MyBoolMethod()
{
//...
return true;
}
}
Simple answer no it is not possible.
The reason is that there are no standalone functions in C# but classes with methods.
Also in other languages like C++ once you start using classes forward declaration of the methods themselves are not needed. It can be that the classes themselves need forward declarations in C++ but since you are talking about methods the comparison still stands.
Bottom line a class is completely defined by its methods in any order they are defined.
You can't really do things like this in C#. I am not sure why you would really want to anyway. Having the declaration and definition in one place is simple and easier to understand
Doing something like this is required in some other languages, but forcing that pattern in C# probably isn't a good idea.
No you can not do it. You can only declare abstract methods like this. Otherwise it will give you an error.
I tried and it gave me
Error 1 'Project.SomeClass.ABC()' must declare a body because it is not marked abstract, extern, or partial
Only abstract methods can be defined like this, abstract methods need only a prototype to be overridden.
This is valid:
public abstract void ABC();
Forward declaration is not possible in C# classes. It's possible only in Interfaces and if your method is abstract. Something like this is allowed
abstract void Draw();

Implementing abstract classes while adding the necessary using directives

Lets assume we have the following abstract base class that declares a parameterized method, whereas the parameter lives in another namespace:
using Example.SubNamespace;
namespace Example
{
public abstract class BaseClass
{
public abstract void Method(Parameter param);
}
}
Following a simple class that acts as our parameter (note the different namespace):
namespace Example.SubNamespace
{
public class Parameter
{
}
}
When implementing a sub class, visual studio offers the option "Implement Abstract Class" when right-clicking the derived class. I've done that in the following example:
namespace Example
{
public class SubClass : BaseClass
{
public override void Method(SubNamespace.Parameter param)
{
throw new System.NotImplementedException();
}
}
}
Call me petty but sometimes it seems very annoying to me having the fully qualified namespaces within the methods signature.
Is there any possibility to implement an abstract class while automatically inserting the correct using directives? Changing these things manually seems like an unnecessary effort to me.
No way to do this. Consider placing your SubClass and BaseClass in the same namespace. I don't think this is a big deal.
You can also use intellisense to add namespaces:
Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Extension methods for sealed class in c#

I have this sealed class,
public sealed class A
{
public string AName {get;set;}
}
and someone can write an extension method for it like this:
public static class Extensions
{
public static void ExtensionMethodForA (this A a)
{
Console.WriteLine("A's Extension method!");
}
}
The question is, how do you prevent that ?
You don't. You can't. And you shouldn't want to.
Instance methods are always preferred to extension methods, so it should not present a conflict. Other than that, they are mere syntax / convenience. Stop trying to make life inconvenient for callers.
You might be confused by the term "extension method". It is not a method in the class or even a derived class; It is an operation on a type. It has no access to the private, protected or internal members of the class hierarchy and therefore the class is still sealed.
So, you can't and don't need to.
There would be no point. Any user could still create a static class which implemented a method which used your class type.
They would just leave out the 'this' out of the declaration, and callers would have to explicitly pass the object, rather than using the simpler . syntax. The end result would be identical.
Extension methods are just a nicer way of expressing what I've just described, which will always be possible anyway.

Categories