C# and Reflection - c#

I'm a brand-newbie to C#, albeit not programming, so please forgive me if I mix things up a bit -- it's entirely unintentional. I've written a fairly simple class called "API" that has several public properties (accessors/mutators). I've also written a testing console application that uses reflection to get an alphabetically list of names & types of each property in the class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using MyNamespace; // Contains the API class
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi");
API api = new API(1234567890, "ABCDEFGHI");
Type type = api.GetType();
PropertyInfo[] props = type.GetProperties(BindingFlags.Public);
// Sort properties alphabetically by name.
Array.Sort(props, delegate(PropertyInfo p1, PropertyInfo p2) {
return p1.Name.CompareTo(p2.Name);
});
// Display a list of property names and types.
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, propertyInfo.PropertyType);
}
}
}
}
Now what I need is a method that loops through the properties and concats all the values together into a querystring. The problem is that I'd like to make this a function of the API class itself (if possible). I'm wondering if static constructors have something to do with solving this problem, but I've only been working with C# for a few days, and haven't been able to figure it out.
Any suggestions, ideas and/or code samples would be greatly appreciated!

This is unrelated to static constructors. You can do it with static methods:
class API {
public static void PrintAPI() {
Type type = typeof(API); // You don't need to create any instances.
// rest of the code goes here.
}
}
You can call it with:
API.PrintAPI();
You don't use any instances when you call static methods.
Update: To cache the result, you can either do it on first call or in an static initializer:
class API {
private static List<string> apiCache;
static API() {
// fill `apiCache` with reflection stuff.
}
public static void PrintAPI() {
// just print stuff from `apiCache`.
}
}

Related

How to call a method from an external Assembly

I have sample c# project:
namespace SampleExe
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
And I have sample c# dll:
namespace SampleDll
{
public class Program
{
public static void TestMethod(string samplestr)
{
Console.WriteLine("TestMethod Void Runned! Your string is: "+samplestr);
}
}
}
How can i call TestMethod() from compilled SampleDll.DLL (i want to load external dll)
Here's a working example of using Reflection to load a library at runtime and execute a static method. Note that it assumes quite a lot: you must know the library name, the class name, the method name, and all of its arguments ahead of time. It's often much easier to just reference a library directly.
A great way to use Reflection successfully is together with inheritance/interfaces. Library A contains the base class or interface, and Library B contains a derived class. Library A can use reflection to load Library B , then find all class types in Library B that are derived from the base class or interface (using Type.IsAssignableFrom). In this way, Library A will have strongly typed properties and methods to work with coming from the base, instead of having to know string names of classes, methods, and properties in Library B a priori.
Code for main EXE doing the reflection:
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace SomeNamespace
{
public class Program
{
static void Main()
{
string pathToSampleDLL = "<if you know the path ahead of time, use it>";
// if SampleDLL.dll is in same directory as this EXE (a common occurrence):
string workingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
pathToSampleDLL = Path.Combine(workingDirectory, "SampleDLL.dll");
// load the DLL at runtime
Assembly sampleDLL = Assembly.LoadFrom(pathToSampleDLL);
// since you know the type name, you can use LINQ to return your type:
Type sampleType = sampleDLL.GetTypes().FirstOrDefault(t => t.Name == "Program");
// you are looking for a static method on this type, and you know its name, so use GetMethods:
MethodInfo staticMethod = sampleType.GetMethod("TestMethod", BindingFlags.Public | BindingFlags.Static);
// invoke the method. Since you know its arguments and return value ahead of time, just hard code it:
// you can use null for the object since this is a static method. It takes only one argument, a sample string
staticMethod.Invoke(null, new object[] { "sampleStr" });
}
}
}
Code for sample library (compiled to "SampleDLL.dll"):
using System;
namespace SampleDll
{
public class Program
{
public static void TestMethod(string sampleStr)
{
Console.WriteLine("TestMethod Void Runned! Your string is: " + sampleStr);
}
}
}
You have multiple options for this. You can create a dll and add the dll as a reference to the project. You can add the project as a reference also. You can create a NuGet package of dll also and use that.
Then simply call SampleDll.Program.TestMethod
To do this, you need to use reflection.
var assembly = Assembly.Load(File.ReadAllBytes("SampleDLL.dll"));
foreach(Type type in assembly.GetExportedTypes())
{
var c = Activator.CreateInstance(type);
type.InvokeMember("TestMethod", BindingFlags.InvokeMethod, null, c, new object[] { #"Hi!" });
}

What is the difference between these using statements of interop in c# [duplicate]

Where or when would one would use namespace aliasing like
using someOtherName = System.Timers.Timer;
It seems to me that it would just add more confusion to understanding the language.
That is a type alias, not a namespace alias; it is useful to disambiguate - for example, against:
using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;
(ps: thanks for the choice of Timer ;-p)
Otherwise, if you use both System.Windows.Forms.Timer and System.Timers.Timer in the same file you'd have to keep giving the full names (since Timer could be confusing).
It also plays a part with extern aliases for using types with the same fully-qualified type name from different assemblies - rare, but useful to be supported.
Actually, I can see another use: when you want quick access to a type, but don't want to use a regular using because you can't import some conflicting extension methods... a bit convoluted, but... here's an example...
namespace RealCode {
//using Foo; // can't use this - it breaks DoSomething
using Handy = Foo.Handy;
using Bar;
static class Program {
static void Main() {
Handy h = new Handy(); // prove available
string test = "abc";
test.DoSomething(); // prove available
}
}
}
namespace Foo {
static class TypeOne {
public static void DoSomething(this string value) { }
}
class Handy {}
}
namespace Bar {
static class TypeTwo {
public static void DoSomething(this string value) { }
}
}
I use it when I've got multiple namespaces with conflicting sub namespaces and/or object names you could just do something like [as an example]:
using src = Namespace1.Subspace.DataAccessObjects;
using dst = Namespace2.Subspace.DataAccessObjects;
...
src.DataObject source = new src.DataObject();
dst.DataObject destination = new dst.DataObject();
Which would otherwise have to be written:
Namespace1.Subspace.DataAccessObjects.DataObject source =
new Namespace1.Subspace.DataAccessObjects.DataObject();
Namespace2.Subspace.DataAccessObjects.DataObject dstination =
new Namespace2.Subspace.DataAccessObjects.DataObject();
It saves a ton of typing and can be used to make code a lot easier to read.
In addition to the examples mentioned, type aliases (rather than namespace aliases) can be handy when repeatedly referring to generic types:
Dictionary<string, SomeClassWithALongName> foo = new Dictionary<string, SomeClassWithALongName>();
private void DoStuff(Dictionary<string, SomeClassWithALongName> dict) {}
Versus:
using FooDict = Dictionary<string, SomeClassWithALongName>;
FooDict foo = new FooDict();
private void DoStuff(FooDict dict) {}
Brevity.
There are fringe benefits to provide clarity between namespaces which share type names, but essentially it's just sugar.
I always use it in situations like this
using Utility = MyBaseNamespace.MySubNamsepace.Utility;
where Utility would otherwise have a different context (like MyBaseNamespace.MySubNamespace.MySubSubNamespace.Utility), but I expect/prefer Utility to always point to that one particular class.
It is very useful when you have multiple classes with the same name in multiple included namespaces. For example...
namespace Something.From.SomeCompanyA {
public class Foo {
/* ... */
}
}
namespace CompanyB.Makes.ThisOne {
public class Foo {
/* ... */
}
}
You can use aliases to make the compiler happy and to make things more clear for you and others on your team:
using CompanyA = Something.From.CompanyA;
using CompanyB = CompanyB.Makes.ThisOne;
/* ... */
CompanyA.Foo f = new CompanyA.Foo();
CompanyB.Foo x = new CompanyB.Foo();
We have defined namespace aliases for all of our namespaces. This makes it very easy to see where a class comes from, e.g:
using System.Web.WebControls;
// lots of other using statements
// contains the domain model for project X
using dom = Company.ProjectX.DomainModel;
// contains common web functionality
using web = Company.Web;
// etc.
and
// User from the domain model
dom.User user = new dom.User();
// Data transfer object
dto.User user = new dto.User();
// a global helper class
utl.SomeHelper.StaticMethod();
// a hyperlink with custom functionality
// (as opposed to System.Web.Controls.HyperLink)
web.HyperLink link = new web.HyperLink();
We have defined some guidelines how the aliases must be named and everyone is using them.
I find the aliases very useful in unit testing. When you are writing unit tests, it is a common practice to declare the subject to test as
MyClass myClassUT;
being myClassUT the subject Under Test. But what if you want to write unit tests for a static class with static methods? Then you can create an alias like this:
using MyStaticClassUT = Namespace.MyStaticClass;
Then you can write your unit tests like this:
public void Test()
{
var actual = MyStaticClassUT.Method();
var expected = ...
}
and you never loose sight of what the subject under test is.
In one way it is really handy while coding in Visual Studio.
Use-case: Let's say I've to use only few classes e.g. SqlConnection from a namespace System.Data. In normal course I'll import the System.Data.SqlClient namespace at the top of the *.cs file as shown below:
using System.Data;
Now look at my intellisense. It is heavily proliferated with whole lot of classes to choose from while typing in code editor. I'm not going to use whole bunch of classes at all:
So I would rather use an alias at the top of my *.cs file and get a clear intellisense view:
using SqlDataCon = System.Data.SqlClient.SqlConnection
Now look at my intellisense view. It is super-clear and super-clean.
One reason I know; It lets you use shorter names when you have name collisions from imported namespaces.
Example:
If you declared using System.Windows.Forms; and using System.Windows.Input; in the same file when you go to access ModifierKeys you might find that the name ModifierKeys is in both the System.Windows.Forms.Control and System.Windows.Input namespaces.
So by declaring using Input = System.Windows.Input; you can then get System.Windows.Input.ModifierKeys via Input.ModifierKeys.
I'm not a C# buff but aliasing namespace seems like "best practise" to me. That way you know what you're getting and still don't have to type too much more.
You can use them to modify a code very easily.
For example:
#if USE_DOUBLES
using BNumber = System.Double;
#else
using BNumber = System.Single;
#endif
public void BNumber DoStuff(BNumber n) {
// ...
}
public void BNumber DoStuff2(BNumber n) {
// ...
}
public void BNumber DoStuff3(BNumber n) {
// ...
}
By the simple change in of the directive you can decide if your whole code works in float or double.

How can I turn a string into a runnable piece of code in c#

In a program I'm creating, I need to be able to convert a string variable into a runnable piece of code in C#.
For example we would have
String code = "console.Writeline("hello");"
function(code);
double function(String var) {
// turn var into code
// run var
}
Any feedback would be much appreciated.
You can use lprun.exe which comes with LINQPad. The documentation explains the usage pretty well.
In summary you pass in your C# (also other languages available) code which is let's say stored in Foo.txt to the executable which is then executed.
lprun.exe -lang=p Foo.txt
p stands for Program see the documentation for more details.
You need to actually compile the method on runtime to use them like this (ie. pass method by string and then compile it).
So for example you can:
Create method on runtime
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
public static class RuntimeHelpers
{
public static MethodInfo CreateFunction()
{
//You can pass it through parameter
string code = #"
using System;
namespace RuntimeFunctions
{
public class Functions
{
public static void PrintStuff(string input)
{
Console.WriteLine(input);
}
}
}";
//Compile on runtime:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), code);
//Compiled code threw error? Print it.
if (results.Errors.HasErrors)
{
foreach (var error in results.Errors)
{
Console.WriteLine(error);
}
}
//Return MethodInfo for future use
Type function = results.CompiledAssembly.GetType("RuntimeFunctions.Functions");
return function.GetMethod("PrintStuff");
}
}
Use it
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
MethodInfo info = RuntimeHelpers.CreateFunction();
//Create delegate to use our function
//If you're gonna create function that actually returns something,
//you need to go for a Func<T, T1> cast instead of Action<T>
var func = (Action<string>)Delegate.CreateDelegate(typeof (Action<string>), info);
func("Hello");
Console.ReadKey();
}
}
Loosely based on article by Lumír Kojecký on: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime

How to construct a call to a method using dynamic

Hi I have a namespace with a lot of classes and all of them has a method Destroy(int id)
I want to call that method using dynamic word.
Here is my example:
public bool DeleteElement<T>(T tElement)
{
Type t = typeof(T);
dynamic element = tElement;
var id = element.Id;
//until here everything is fine
//here I want to say
(namespace).myClassName.Destroy(id);
//the name of myClassName is like t.ToString()
}
I can avoid namespace including a using at the top. The idea is to call that static method using dynamic, not Reflection, please see that Destroy is a static method of T. I need something like this T.Destroy(id)
If Destroy(int id) is a static method, couldn't you create an instance method that would call the static one?
public void Destroy()
{
ThisClass.Destroy(this.Id);
}
You could then define an IDestroyable interface implemented by all these classes:
interface IDestroyable { void Destroy(); }
And then modify your DeleteElement method as follows:
public bool DeleteElement<T>(T tElement) where T : IDestroyable
{
tElement.Destroy();
}
No need to use dynamic here... Actually, using dynamic in this situation is often an indication of bad design. It's quite rare to actually need dynamic except in the scenarios for which it was created (e.g. interop with dynamic languages)
(If the classes are generated but they have the partial modifier, you can declare the new method in another file that is not touched by the generator)
EDIT: if the classes are generated and are not partial, you can't modify them... So another solution would be to use reflection; I know you want to avoid that (for performance reasons I assume), but you can limit the performance impact by doing the reflection only once for each type: you just need to create and cache a delegate for each type.
class DestroyHelper<T>
{
static readonly Action<int> _destroy;
static readonly Func<T, int> _getId;
static DestroyHelper()
{
var destroyMethod = typeof(T).GetMethod("Destroy", BindingFlags.Static | BindingFlags.Public);
_destroy = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), destroyMethod);
var getIdMethod = typeof(T).GetProperty("Id").GetGetMethod();
_getId = (Func<T, int>)Delegate.CreateDelegate(typeof(Func<T, int>), getIdMethod);
}
public static void Destroy(T element)
{
_destroy(_getId(element));
}
}

C# namespace alias - what's the point?

Where or when would one would use namespace aliasing like
using someOtherName = System.Timers.Timer;
It seems to me that it would just add more confusion to understanding the language.
That is a type alias, not a namespace alias; it is useful to disambiguate - for example, against:
using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;
(ps: thanks for the choice of Timer ;-p)
Otherwise, if you use both System.Windows.Forms.Timer and System.Timers.Timer in the same file you'd have to keep giving the full names (since Timer could be confusing).
It also plays a part with extern aliases for using types with the same fully-qualified type name from different assemblies - rare, but useful to be supported.
Actually, I can see another use: when you want quick access to a type, but don't want to use a regular using because you can't import some conflicting extension methods... a bit convoluted, but... here's an example...
namespace RealCode {
//using Foo; // can't use this - it breaks DoSomething
using Handy = Foo.Handy;
using Bar;
static class Program {
static void Main() {
Handy h = new Handy(); // prove available
string test = "abc";
test.DoSomething(); // prove available
}
}
}
namespace Foo {
static class TypeOne {
public static void DoSomething(this string value) { }
}
class Handy {}
}
namespace Bar {
static class TypeTwo {
public static void DoSomething(this string value) { }
}
}
I use it when I've got multiple namespaces with conflicting sub namespaces and/or object names you could just do something like [as an example]:
using src = Namespace1.Subspace.DataAccessObjects;
using dst = Namespace2.Subspace.DataAccessObjects;
...
src.DataObject source = new src.DataObject();
dst.DataObject destination = new dst.DataObject();
Which would otherwise have to be written:
Namespace1.Subspace.DataAccessObjects.DataObject source =
new Namespace1.Subspace.DataAccessObjects.DataObject();
Namespace2.Subspace.DataAccessObjects.DataObject dstination =
new Namespace2.Subspace.DataAccessObjects.DataObject();
It saves a ton of typing and can be used to make code a lot easier to read.
In addition to the examples mentioned, type aliases (rather than namespace aliases) can be handy when repeatedly referring to generic types:
Dictionary<string, SomeClassWithALongName> foo = new Dictionary<string, SomeClassWithALongName>();
private void DoStuff(Dictionary<string, SomeClassWithALongName> dict) {}
Versus:
using FooDict = Dictionary<string, SomeClassWithALongName>;
FooDict foo = new FooDict();
private void DoStuff(FooDict dict) {}
Brevity.
There are fringe benefits to provide clarity between namespaces which share type names, but essentially it's just sugar.
I always use it in situations like this
using Utility = MyBaseNamespace.MySubNamsepace.Utility;
where Utility would otherwise have a different context (like MyBaseNamespace.MySubNamespace.MySubSubNamespace.Utility), but I expect/prefer Utility to always point to that one particular class.
It is very useful when you have multiple classes with the same name in multiple included namespaces. For example...
namespace Something.From.SomeCompanyA {
public class Foo {
/* ... */
}
}
namespace CompanyB.Makes.ThisOne {
public class Foo {
/* ... */
}
}
You can use aliases to make the compiler happy and to make things more clear for you and others on your team:
using CompanyA = Something.From.CompanyA;
using CompanyB = CompanyB.Makes.ThisOne;
/* ... */
CompanyA.Foo f = new CompanyA.Foo();
CompanyB.Foo x = new CompanyB.Foo();
We have defined namespace aliases for all of our namespaces. This makes it very easy to see where a class comes from, e.g:
using System.Web.WebControls;
// lots of other using statements
// contains the domain model for project X
using dom = Company.ProjectX.DomainModel;
// contains common web functionality
using web = Company.Web;
// etc.
and
// User from the domain model
dom.User user = new dom.User();
// Data transfer object
dto.User user = new dto.User();
// a global helper class
utl.SomeHelper.StaticMethod();
// a hyperlink with custom functionality
// (as opposed to System.Web.Controls.HyperLink)
web.HyperLink link = new web.HyperLink();
We have defined some guidelines how the aliases must be named and everyone is using them.
I find the aliases very useful in unit testing. When you are writing unit tests, it is a common practice to declare the subject to test as
MyClass myClassUT;
being myClassUT the subject Under Test. But what if you want to write unit tests for a static class with static methods? Then you can create an alias like this:
using MyStaticClassUT = Namespace.MyStaticClass;
Then you can write your unit tests like this:
public void Test()
{
var actual = MyStaticClassUT.Method();
var expected = ...
}
and you never loose sight of what the subject under test is.
In one way it is really handy while coding in Visual Studio.
Use-case: Let's say I've to use only few classes e.g. SqlConnection from a namespace System.Data. In normal course I'll import the System.Data.SqlClient namespace at the top of the *.cs file as shown below:
using System.Data;
Now look at my intellisense. It is heavily proliferated with whole lot of classes to choose from while typing in code editor. I'm not going to use whole bunch of classes at all:
So I would rather use an alias at the top of my *.cs file and get a clear intellisense view:
using SqlDataCon = System.Data.SqlClient.SqlConnection
Now look at my intellisense view. It is super-clear and super-clean.
One reason I know; It lets you use shorter names when you have name collisions from imported namespaces.
Example:
If you declared using System.Windows.Forms; and using System.Windows.Input; in the same file when you go to access ModifierKeys you might find that the name ModifierKeys is in both the System.Windows.Forms.Control and System.Windows.Input namespaces.
So by declaring using Input = System.Windows.Input; you can then get System.Windows.Input.ModifierKeys via Input.ModifierKeys.
I'm not a C# buff but aliasing namespace seems like "best practise" to me. That way you know what you're getting and still don't have to type too much more.
You can use them to modify a code very easily.
For example:
#if USE_DOUBLES
using BNumber = System.Double;
#else
using BNumber = System.Single;
#endif
public void BNumber DoStuff(BNumber n) {
// ...
}
public void BNumber DoStuff2(BNumber n) {
// ...
}
public void BNumber DoStuff3(BNumber n) {
// ...
}
By the simple change in of the directive you can decide if your whole code works in float or double.

Categories

Resources