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

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

Related

Can I restrict the visibility of C# extension methods to classes in the same assembly?

Say I have these files:
MyCode.cs
namespace MyCodeNamespace
{
public class MyClass
{
//OMITTED
}
internal static class MyExtensions
{
internal static void Foo(this string str)
{
//OMITTED
}
}
}
OtherCode.cs
using MyCodeNamespace;
namespace OtherCodeNamespace
{
//OMITTED
}
The two files are part of the same assembly. Is there any way I can make Foo accessible to MyCode.cs but not to OtherCode.cs? My question is similar to this question:
C# Extension Methods only visible and accessible within one class ("private")
But its accepted answer isn't really what I'm looking for. I want to make an extension method that's only visible to the code I'm working on, and according to the answer to the above question, someone could still access it by adding a "using" statement. Is there a way I can create an extension method that is only visible to my code, and nowhere else, not even by another class in the same assembly?
I ask because the syntax for calling an extension method is handy and would be useful for what I'm working on (otherwise I'd just create a private method instead), but I don't want others to see it and use it from their code in case it doesn't do what they assume it does. And thanks to Visual Studio's intellisense, my extension methods are currently showing up in the list of available methods (along with the option to add the namespace they're in).
There is no such thing as a namespace-limited access modifier in the .NET platform. From the docs
public : Access is not restricted.
protected : Access is limited to the containing class or types derived from the containing class.
Internal : Access is limited to the current assembly.
protected internal: Access is limited to the current assembly or types derived from the containing class.
private : Access is limited to the containing type.
That's all you have to work with. So the answer is no.
Extension methods are just semantic sugar that compile to the same IL as calling the static helpers directly.
MyExtensionMethods.DoSomething(myObject);
myObject.DoSomething();
You cannot restrict it from being called, but you can remove its visibility from Intellisense.
Simply move your extension methods to a different namespace, add a using statement in your MyCode.cs and don't include that namespace in OtherCode.cs
[update]
If you really need to restrict the caller, you could try using reflection to determine and restrict, but this is a bit overkill. Best to simply use a private static helper instead of doing this.
var frame = new System.Diagnostics.StackFrame(1, false);
var method = frame.GetMethod();
var type = method.DeclaringType;
// allow|deny type
I had a similar problem. I did not want the programmer to see my inner extension methods when configuring services in ASP.NET Core.
The solution for me was to add all extension methods to namespace Microsoft.Extensions.DependencyInjection that is used in Startup.cs and the user can see those methods. (As you would always do.)
If I wanted to "hide" something I added the extension method to MyNamespace.Extensions. If the user writes the correct name the helper for add using will show up but by default it won't be listed.
I know this is not a solution but might help someone.
think about similar thing;
c# assembly, friend assembly
will try InternalsVisibleTo;
if your classes is closed maybe will not helpfull but you can try it;

Static Class or Objects [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to Use Static Classes in C#
sorry if the question is meaningless or stupid am trying to create a windows service in which i have few class files each class file has some functions that calls another class file.
For example
class file one has a method to create email like
public bool CreateEmail()
{
try
{
//code here
}
catch (Exception ex)
{
//Write to Log
to create log call function from **another class file**
}
}
and many more calls like this.I would like to know if Using static class is better or creating object for each class and calling the methods will be better.Which is the recommended way?
Ask yourself
How relevant is this method to your object.
Does it alter the state of your object in anyway.
If its relevant and does change your object state ,then you should have the method inside the class.If not then you dont need to have that method in your class
In your case from the look of it,its quite clear that its not going to alter any state,rather it needs some information from the other object to send the mail.So i would definitely make this a util class(static class) and use it whenever i need.
Think about:
Do you need to do unit test, if yes, static class is not good and cannot be mocked in case you follow design for test ability.
Single responsibility principle, don't put every method into one so-called utility class. Group methods in separate classes which are relevant together and follow SRP.
Classes should have meaningful names. Utility, util or helper are not meaningful names
If you are only using the class files to group the methods, and wont be needing instances of the class for anything other than calling those methods, then you should use a static class - thats what they are for.
I would like to know if Using static class is better or creating object for each class and calling the methods will be better.
If it is a multi-threaded environment and logging requires some data to be shared across multiple calls, Create separate instance for each call. otherwise, go for static class and methods.

How to force a C# class to have a constant value in it? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a way to force a C# class to implement certain static functions?
Consider a class and consider that, for some reasons, you need to force this class to have a constant inside it. This is to be applied to a whatever set of classes. In my specific case I need some classes of mine to have a constant inside them to hold the corresponding null value.
Those classes that, in my case, implement a certain interface because they must behave in a certain way, must also have three special values that are needed in my context (context that is too long to explain and quite useless here).
So basically I need a way to force my classes to have a certain constant inside them (accessible from outside). I know that I could simply put the constant in those classes, but what if I am looking for a way to tell the compiler: "If this class implements this interface (for example), that you should not compile it if there is not that constant!".
In this way there is the compiler checking, and not just the programmer who might forget to put the constant.
I hope I could explain my problem. Thanks in advance.
So basically I need a way to force my classes to have a certain
constant inside them (accessible from outside). I know that I could
simply put the constant in those classes, but what if I am looking for
a way to tell the compiler: "If this class implements this interface
(for example), that you should not compile it if there is not that
constant!".
You can achieve something like this creating a class containing an unique public constructor which requires all the information/values you need.
So for example you could use something like:
class myClass{
public readonly int Value1;
public readonly string Value2;
public myClass(int value1, string value2){
Value1 = value1;
Value2 = value2;
}
}
Infact in this case the programmer is forced to instantiate the object giving the right values to the unique constructor available, and can't change the value of the two public fields (due to the readonly keyword).
Explanation from a previous question on the same topic:
A call to a static method is done through the class name, not through
an object reference, and the IL code to call it will call the abstract
method through the name of the class that defined it, not necessarily
the name of the class you used.
Previous post: Why can't I have abstract static methods in C#?
What is wrong with just adding the static method into the class? I don't see why you need another layer when its perfectly logical to code in the static method directly into the class.
public class MyClass {
public static MyClass TheMethod(int i){
// TODO:
}
}

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.

When to use this keyword as function argument [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does “this” mean in a static method declaration?
i go through a code snippet and found this keyword is used as function argument.
the code snippet is like
public static void AddCell(this Table table, object cell)
why AddCell has this keyword they can write likeAddCell(Table table, object cell)
please explain the situation when to use this keyword as function argument with small code sample as a result i can better understand. thanks.
Basically what is being defined in your example is an extension method. In a static method, if you define the first argument using the this keyword you are allowing the method to be called on instance objects of the type defined on the first argument.
In the example you stated you would be able to do something like this:
Table someTableInstance; /// must be instanciated somehow;
someTableInstance.AddCell(cell); // Call the AddCell method as if it was an instance method.
Hope it helps,
Regards,
Bruno
This syntax is used for extension methods.
These look a bit odd when you first see them written, but they are fabulous things - most of Linq is written as extension methods.
Here's a good intro tutorial - http://csharp.net-tutorials.com/csharp-3.0/extension-methods/ - which includes the example:
public static class MyExtensionMethods
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
which enables you to call:
"fred".IsNumeric()
this is the keyword for creating extension methods.
This way, while I have not changed the implementation of Table, I can call method AddCell on a member of Table.
MSDN:
Extension methods enable you to "add"
methods to existing types without
creating a new derived type,
recompiling, or otherwise modifying
the original type. Extension methods
are a special kind of static method,
but they are called as if they were
instance methods on the extended type.
For client code written in C# and
Visual Basic, there is no apparent
difference between calling an
extension method and the methods that
are actually defined in a type.
It's a declaring an extension method. The point is that as well as
MyStaticClass.AddCell(table, cell);
you can now just call
table.AddCell(cell);
assuming MyStaticClass is in the current namespace or namespaces you've usinged.
The 'this' keyword is used to create an extension method. For instance, if you are using a library class that you want to add a method to without inheriting a new derived type, you can create a static extension method. It is syntactical-sugar that places a regular static method onto an already known type.
For example:
public static int ToNumber( this string numberString )
{
int convertedInt = 0;
// logic goes here to convert to an int
return convertedInt;
}
Can be called like this:
string myNumberString = "5";
int num = myNumberString.ToNumber();
You didn't have to create an inherited class to do this but it reads cleanly.

Categories

Resources