How to extend a static class in C# [duplicate] - c#

This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 2 years ago.
I'm using Microsoft's Visual Studio unit testing framework (the project does therefore I have to). I'm sorely missing some of the more advanced assertions such as AreElementsEqual you find in MBUnit.
I'd like to make them.
As the class is static I can't inherit from it (to create a SuperAssert) and I can't add an extension method (as they're static methods).
I don't want to simply create another class and expect consumers to use the two different ones. How can I expand the class?

You can't. You will have to create a new one.
Or you could create an existing package, like Fluent Assertions.

As the class is static, you cannot as you say, use extension methods to 'add' further methods to the class.
The closest you can do within reason is the following:
public static class AssertExtensions
{
public static void SuperAssert(bool expression)
{
// etc...
}
}
If you are producing a tool library, asking the user to use another class should not be a problem.
If you are still concerned, why not create a base class for your test and have the users use methods within that for asserts?
For instance:
public class TestBase
{
protected void AreEqual(object obj1, object obj2)
{
Assert.AreEqual(obj1, obj2); // etc...
}
protected void SuperAssert(bool expression)
{
// etc...
}
}

Related

"friend" classes in C# and the state pattern [duplicate]

This question already has answers here:
Closed 10 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
Why does C# not provide the C++ style ‘friend’ keyword?
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!
Example: To be placed in AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
The closest equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
or if you prefer to put the Inner class in another file:
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
The public key is optional, depending on your needs.

Need to instantiate class from dll to use in other project [duplicate]

This question already has answers here:
Easiest way to re-use a function without instantiation a new class
(4 answers)
Closed 5 years ago.
I've created a dll, lets call it ExampleHelper.dll.
The structure of the Visual Studio Class Library which I've compiled to dll is the following:
namespace ExampleHelper
{
public class Example
{
public string GetExamples(string input)
{
// stuff
}
}
}
So, I reference it in my other project in which I want to use these ExampleHelper classes, by adding a using line at the top of the file in question:
using ExampleHelper;
Now, I can see that I can access the class from ExampleHelper, which is called Example. But, I can't access the methods in that class, which means I can't write Example.GetExamples("hello"), as it says GetExamples doesn't exist.
I noticed that I can do this:
Example e = new Example();
e.GetExamples("hello");
which I of course can use, but it doesn't feel quite right to instantiate a new object each time I want to use a helper method.
Have I done something completely wrong? My guess is yes, but I can't find where I'm going wrong. Any help appreciated!
Make GetExamples(string input) a static method
public static string GetExamples(string input)
Static methods do not require an instance of the class.
You need to have an instance of Example object to call this method.
To call a method without an instace of a object, method must be static.
public static string GetExamples(string input)
should be the method's declaration.
Please put your class and methods as STATIC, you'll be able to use it everywhere.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static

C# static class why use? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I set my classes as static a lot, but I am not sure when use static or not, or what's the difference it makes to use it or not.
can anybody explain please?
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.

Very Simple Extension Methods Explanation in Layman's terms (C#) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are Extension Methods?
I know this questions has been asked previously, but could some provide a non-techy explanation, as simple as possible in laymens terms.
All of documentation on other answers seems to be a little far out for me
Extension methods are a way of simulating new methods on a type without actually changing the type definition itself.
I guess a layman way of explaining it is that it gives every type it's own personal entourage. They person itself is not modified they just gain a host of new abilities simply by virtue of the people who are paid to hang out with them.
I don't think it gets much simpler than the one sentence from the Wikipedia article:
"Extension methods enable you to 'add' methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type."
Well, programming is inherently "techy", so I would try to learn as much as you can in order to understand the documentation. However, extension methods simply allow you to add methods that act like instance methods to an existing class that would otherwise be closed for modification.
For example, if I wrote a library that included a type Foo and did not distribute the source code you would be stuck subclassing it to add any functionality, and that would only be possible if I left the type "unsealed". With the advent of extension methods you are able to add methods to the class that you can call as you would any other method (in reality they are implemented as static methods that take a hidden first parameter to an instance of Foo, so you still don't have access to private members of the class).
Extension methods allow you to add functionality (methods) to classes you have no access to their source.
You can define a simple class:
public class A
{
public void B()
{
Console.WriteLine("B called");
this.C();
}
public void C()
{
Console.WriteLine("C called");
}
}
But what if you get A defined as:
public class A
{
public void C()
{
Console.WriteLine("C called");
}
}
And you want to add function B to it? You use extension methods to do it:
public class A
{
public void C()
{
Console.WriteLine("C called");
}
}
// the extensions class, can be any name, must be public
public class Extensions
{
public static void B( this A me)
// ^ must be public static ^ indicates extension ^ type to extend ^ name of variable instead of this
{
Console.WriteLine("B called");
// instead of this, you use the name of variable you used in the parameters
me.C();
}
}
Now you can call A.B() as it was in the first example.

extension method to extend static class [duplicate]

This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 8 years ago.
I am wondering if I can use extension method or other techniques to extend static class like
System.Net.Mime.MediaTypeNames.Image, it has fewer type than I need.
No, extension methods can only be used to add instance methods, not static methods (or even properties). Extension methods are really just syntactic sugar around static methods. For instance, when you use an extension method such as Count():
var list = GetList();
var size = list.Count();
This is actually compiled to:
var list = GetList();
var size = Enumerable.Count(list);
You can't add additional static methods to an existing class using extension methods.
No, this is not yet possible in C#, though hopefully it will become so at some point. And you can't subclass a static class and add new methods that way, since static classes must derive from object. One thing you can do though, which produces a pretty similar effect in your code, is simply declare another static class that you will use instead when you want your extension methods. For example:
public static class MessageBox2
{
public static DialogResult ShowError(string Caption, string Message, params object[] OptionalFormatArgs)
{
return MessageBox.Show(string.Format(Message, OptionalFormatArgs), Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Since the original class is static, by definition the "extension" method doesn't need to receive an instance as a this parameter, and can simply use static methods of the original class.

Categories

Resources