How to add an extension method to the MessageBox - c#

it's possible?
based in another's examples, as LabelExtesios, StringExtensions, etc.
I wrote this:
namespace MessageBoxExtensions
{
public static class MessageBoxExtensionsClass
{
public static void Foo()
{
}
}
}
then:
using MessageBoxExtensions;
// ...
MessageBox.Foo();
gin an error: MessageBox.Foo();
'System.Windows.Forms.MessageBox' does not contain a definition for 'Foo'

Description
You cant do this because System.Windows.Forms.MessageBox is NOT an instance of MessageBox. MessageBox.Show() is a static method.
You cant create an instance of MessageBox because this class has no public constructor.
Update
But you can create your own class in the System.Windows.Forms namespace and use the
MessageBox in this method like this
Sample
namespace System.Windows.Forms
{
public static class MyCustomMessageBox
{
public static void Foo()
{
MessageBox.Show("MyText");
}
}
}
MyCustomMessageBox.Foo();

You are missing the this keyword from your extension method declaration.
But because System.Windows.Forms.MessageBox does not have a public constructor just static factory methods (which returns DialogResult) so you won't able the create a standalone MessageBox instance to invoke your extension method on it.
So to answer the your question:
Yes it's possible to create an extension method on MessageBox (see other answers) but you can't invoke it by MessageBox.Foo() you need an instance of MessageBox what you cannot create so it won't work.

You need to add a parameter of type MessageBox to the extension method:
public static void Foo(this MessageBox messageBox) { ... }
Then create an instance of the MessageBox before calling the method
var messageBox = new MessageBox();
messageBox.Foo();
[Update:
Unfortunately this doesn't work in case of the MessageBox since there is no public constructor. Thanks to nemesv for the hint. The following example should theoretically work, but in practice it won't. I'll leave it for reference.]
In your example you call the method on the class itself. Extension methods only apply to instances. Here's a version of your code with the above corrections applied:
namespace MessageBoxExtensions
{
public static class MessageBoxExtensionsClass
{
public static void Foo(this MessageBox messageBox)
{
// ...
}
}
}
using MessageBoxExtensions;
// ...
var messageBox = new MessageBox();
messageBox.Foo();

You must qualify the extension method parameter with a this modifier for it to be registered as an extension method.
namespace MessageBoxExtensions
{
public static class MessageBoxExtensionsClass
{
public static void Foo(this MessageBox messagebox)
{
}
}
}

Related

How to fix "Does not exist" when calling a static function from another class?

I want to call a static void function from another class, but it's said
The name [funcion name here] does not exist in the current context
Each class is in the same project, Framework 4.5.2
Its a public static void Function, in a public static class, don't see why it's not working.
The class where a function located, I want to call:
namespace Client.Modules
{
public static class Login
{
public static void Run()
{
// do something
}
}
}
The class where I want to call:
using Client.Modules;
namespace Client
{
public class Main
{
Login.Run(); // here
}
}
public class Main
{
Login.Run(); // here
}
That’s invalid: You can’t generally execute code outside methods. The only things that can go directly into classes are declarations. Put Login.Run() inside a method.

Add method to a class from another project

Is it possible to add a method to a class from another project?
I have a class:
namespace ProjectLibrary
{
public class ClassA
{
// some methods
}
}
I want to add a method to save my object in a file, but I don't want to add this method in my project ProjectLibrary because I don't want to add reference to System.IO (I want to use this project for android application and PC application).
Is there a possibility to add a method SaveToFile() usable only in another project? Or create an abstract method in ClassA but define it in other project.
Like this :
using ProjectLibrary;
namespace ProjectOnPC
{
void methodExample()
{
ClassA obj = new ClassA();
// do something
obj.SaveToFile();// => available only in namespace ProjectOnPC
}
}
Thank you for help
You can use extension methods.
Example:
namespace ProjectOnPC
{
public static void SaveToFile(this Class myClass)
{
//Save to file.
}
}
The thing You are looking for is called Extension method:
DotNetPerls
MSDN link
What are Extension Methods?
Code for base class:
namespace ProjectLibrary
{
public ClassA
{
// some methods
}
}
Extension method:
using ProjectLibrary;
namespace ProjectOnPC
{
void SaveToFile(this ClassA Obj, string Path)
{
//Implementation of saving Obj to Path
}
}
Calling in Your program:
using ProjectLibrary;
using ProjectOnPc; //if You won't include this, You cannot use ext. method
public void Main(string[] args)
{
ClassA mObj = new ClassA();
mObj.SaveToFile("c:\\MyFile.xml");
}
You can create an extension method for this purpose.
Here's an example.
In your ProjectOnPc namespace create a class like this:
public static class ClassAExtension
{
public static void SaveToFile(this ClassA obj)
{
// write your saving logic here.
// obj will represent your current instance of ClassA on which you're invoking the method.
SaveObject(obj).
}
}
You can learn more about extension methods here:
https://msdn.microsoft.com/en-us//library/bb383977.aspx

Register a method in another class to a static class?

Is there any possibilities to register a method in another class to a static class in C#, so that i can call that class using the static class name.
Example
public static class StaticClass
{
}
public static class Sample
{
public static string method1()
{return "";}
}
I want to call like this,StaticClass.method1().
First of all,IS IT VALID or Not? or Is there any possible way to do that?
First of all,IS IT VALID or Not?
Sure it's valid; just not the way you're portraying it.
Is there any possible way to do that?
One approach would be to build a method on StaticClass called method1. Maybe you want to encapsulate some default behavior:
public static class StaticClass
{
public static string method1()
{
// do what you need
Sample.method1();
}
}

Static initialization of inherited static member

Consider this example code:
public class A<T>
{
public static T TheT { get; set; }
}
public class B : A<string>
{
static B() {
TheT = "Test";
}
}
public class Program {
public static void Main(String[] args) {
Console.WriteLine(B.TheT);
}
}
Here B.TheT is null. However, changing the Main method like this:
public static void Main() {
new B();
Console.WriteLine(B.TheT);
}
B.TheT is "Test", as expected. I can understand that this forces the static constructor to run, but why does this not happen for the first case?
I tried reading the spec, and this caught my attention (§10.12):
[...] The execution of a static constructor is triggered by the first of the
following events to occur within an application domain:
• [...]
• Any of the static members of the class type are referenced.
My interpretation of this is that since TheT is not a member of B, the static constructor of B is not forced to be run. Is this correct?
If that is correct, how would I best let B specify how to initialize TheT?
A.TheT is "Test", as expected. I can understand that this forces the static constructor to run, but why does this not happen for the first case?
Basically, you haven't really referenced B. If you look in the IL, I think you'll find that your code was actually equivalent to:
public static void Main(String[] args) {
Console.WriteLine(A<string>.TheT);
}
The compiler worked out that that's really the member you meant, even though you wrote B.TheT.
If that is correct, how would I best let A specify how to initialize TheT?
I would try to avoid doing this to start with, to be honest... but you could always just add a static method to B:
public static void Initialize() {
// Type initializer will be executed now.
}
Static constructor is called before the first access or at the latest when the first access is made. I.e you know it has been called when first access is made but not how long before. However, if no access is made it won't be called. So you cannot control when only if it s called.
As per MSDN reference
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
In second case called static contructor and it will call the actual types' static contructor, and not that one of derived one. So in your case it calls the static ctor of the A<T> =>A<string> and not of A.
To prove this behaviour just do the following:
public class Base {
static Base() {
"Base static".Dump();
}
}
public class Derived : Base {
static Derived() {
"Derived static".Dump();
}
public static string temp = "Hello";
}
and call
Derived.temp.Dump();
You will get:
Derived static
Hello
This is what you actually do in your code, you acess derived type A<string> and it's default static ctor is called.

C# any way of accessing the class name of a static class via code?

Within a static class you cannot use the keyword "this" so I can't call this.GetType().GetFullName if I have
public static class My.Library.Class
{
public static string GetName()
{
}
}
Is there anything I can call from within GetName that will return My.Library.Class
you can get the type of a predetermined class with:
typeof(My.Library.Class).FullName
If you need "the class that declares this method", you'll need to use
MethodBase.GetCurrentMethod().DeclaringType.FullName
However, there's a chance this method will be inlined by the compiler. You can shift this call to the static constructor / initialiser of the class (which will never be inlined - log4net recommends this approach):
namespace My.Library
public static class Class
{
static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName;
public static string GetName()
{
return className;
}
}
}
Applying [MethodImpl(MethodImplOptions.NoInlining)] might help, but you should really read up on that if you considering it
HTH - Rob
MethodBase.GetCurrentMethod().DeclaringType.FullName
typeof(My.Library.Class).FullName

Categories

Resources