How do I extract the results of a multicast delegate at runtime? - c#

Not sure if this is possible but im wondering how I catch the return of two methods that are assigned to the same delegate (multicast). I basically wondered if there is a way to catch each return value? Perhaps I have to iterate over it, not really sure..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MutiCastDelegate2
{
class Program
{
delegate string HelloWorldDelegate();
static void Main(string[] args)
{
HelloWorldDelegate myDel1 = ReturnHelloWorld;
HelloWorldDelegate myDel2 = ReturnHelloWorld2;
HelloWorldDelegate myMultiDelegate = myDel1 + myDel2;
Console.WriteLine(myMultiDelegate());
Console.ReadLine();
}
public static string ReturnHelloWorld()
{
return "Return Hello World";
}
public static string ReturnHelloWorld2()
{
return "Return Hello World 2";
}
}
}

You can use MulticastDelegate.GetInvocationList() to get access to each delegate in the list, then you just have to call each one and retrieve the results:
var delegates = myMultiDelegate.GetInvocationList();
foreach (var d in delegates)
{
string result = (string) d.DynamicInvoke();
}

Related

(C#) Type or namespace list could not be found while using system.Collections.generic

I have an issue with creating lists in C#. It says that the type or namespace "file<>" could not be found. I am using System.Collections.Generic and creating the list "correct" as far as I know.
I have basically nothing yet besides the list (worked with array earlier but it didn't meet the requirements):
using System;
using System.IO;
using System.Collections.Generic;
namespace Week_3_Opdracht_3
{
class Program
{
public list<string> streamReaderResults = new list<string>();
private static string currentFileLine;
static void Main(string[] args)
{
StreamReader opdrachtDrieFile = new StreamReader(#"C:\Users\sande\Documents\VisualStudio school\.txt files to read\Opdracht 3 tekst.txt");
while ((currentFileLine = opdrachtDrieFile.ReadLine()) != null)
{
//nothing yet.
}
Console.ReadKey();
}
}
}
From what I know, you create a list by typing "list [name of the list] = new list();". However, this doesn't work. Why am I receiving this error message?
C# is a case-sensitive language, so you need to watch casing. Also, Main in your program is a static method, and can only access static members of the Program class. So you need to mark the List<T> as static:
namespace Week_3_Opdracht_3
{
class Program
{
public static List<string> streamReaderResults = new List<string>();
private static string currentFileLine;
static void Main(string[] args)
{
StreamReader opdrachtDrieFile = new StreamReader(#"C:\Users\sande\Documents\VisualStudio school\.txt files to read\Opdracht 3 tekst.txt");
while ((currentFileLine = opdrachtDrieFile.ReadLine()) != null)
{
//nothing yet.
}
Console.ReadKey();
}
}
}
You need to make list to static.
public static List<string> streamReaderResults = new List<string>();

How do I do unit tests in Visual Studio 2015

I have like below.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Syncfusion.Gitlab
{
public class Branches
{
public void CreateBranch(List<string> projectName, string sourceBranch, string destinationBranch)
{
}
public void CreateTag(List<string> projectName, string sourceBranch,string tagname)
{
}
public static List<string> GetBranchList(string projectId)
{
}
public static List<ProjectData> GetProjectList()
{
}
}
public class ExcelOperation
{
public void GenerateExcel(List<ProjectDetails> finalExcelData, List<string>projectUrl,List<string>tagsorBranchUrl)
{
}
}
}
I can able to test the method and got the positive output. But I do not know how to test these two method public static List<string> GetBranchList(string projectId), public static List<ProjectData> GetProjectList()
My sample test code is below. Below method is successfully passed in NUnit test.
[TestMethod]
public void CreateTags()
{
List<string> project = new List<string>();
project.Add("test1");
string sourceBranch = "master";
string tagsName = "v1.0.0";
branch.CreateTag(project, sourceBranch, tagsName);
}
How can I test the that two methods?
Update:
I can get the answer with the help of first answer. But Now I have anouther doubt.
How could I test for wrong input? I mean I know that the input I was given Is wrong but I need the green tick mark for that testing. That means the input given is wrong so the output also wrong therfore the testing is right.
In my below image. I need public void GetBranchListforWrongInput() also green tick mark.
How could I do it?
Unit testing static method is pretty much as same as testing non-static methods. It might get complex based on what logic you have in the static method.
But simplest way for your case would be as following.
[TestMethod]
public void TestGetBranchList()
{
string projectId = "someProjectId";
var result = Branches.GetBranchList(projectId);
//Assert if result has expected result.
}
[TestMethod]
public void TestGetProjectList()
{
var result = Branches.GetProjectList();
//Assert if result has expected result.
}
[TestMethod]
public void TestCreateBranch()
{
//Prepare TestData
List<string> projectName = new List<string> {"someProject"};
string sourceBranch = "sourceBranch"
string destinationBranch = "destBranch";
Branches branchesObj = new Branches();
// Call method by passing the test data.
branchesObj.CreateBranch(projectName, sourceBranch, destinationBranch);
}
This should help you resolve your issue.

Method calling does not accept char input

I want to obtain the Unicode code of a certain char. The declared function does not accept the argument.
the code blocks at line string str01 = GetEscapeSequence(char c1);
The error:
Error CS1525: Unexpected symbol c1', expecting.' (CS1525)
The code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace problem_005
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Insert the caracter");
char c1 = char.Parse(Console.ReadLine());
string str01 = GetEscapeSequence(char c1);
Console.WriteLine("the Unicode is ={0}", str01);
Console.WriteLine("m");
}
public string GetEscapeSequence(char c)
{
return "\\u" + ((int)c).ToString("X4");
}
}
}
To call a method in C#, you don't need to specify the parameter type. Just
string str01 = GetEscapeSequence(c1);
will suffice.
Also, as main is a static method, you must make GetEscapeSequence static as well:
public static string GetEscapeSequence(char c)

Calling specific namespace and class using Strings

I am currently writing a program in C#, this program has a folder called Classes, many subfolders named a - f, and actual cs files within that folder named aa - cc.
a-f are namespaces
aa-cc are classes.
So if I wanted to invoke a method from Classes\b\bb.cs I'd have to type every time
b.bb,methodName();
It will also generate two Strings which will decide what we are going to be executing.
String myType = "b";
String myClass = "bb";
String toReturn = "";
There are many combinations of myType and myClass so I've had to write a lot of if loops
if (myType.equals("b") && myClass.equals("bb") return toReturn = b.bb.myMethod();
if (myType.equals("b") && myClass.equals("aa") return toReturn = b.aa.myMethod();
this is quite a lot of typing and I feel like there is an easier way to do this since I already know what know what namespace I want to access and what method I want to call.
Is there any way I could do something like
myType.myClass.myMethod()
where myType is the namespace, and myClass is the class I wish to call. This would avoid me typing out ever possible combination.
Improved sample with delegates. Homework: add hash to store delegates in GetDelegate method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TestConsole.Data;
namespace NamespaceA
{
public class ClassAB
{
public void MyMethod()
{
Console.WriteLine("You invoke NamespaceA.ClassAB.MyMethod");
}
public static void MyStaticMethod()
{
Console.WriteLine("You invoke NamespaceA.ClassAB.MyStaticMethod");
}
}
}
namespace TestConsole
{
public delegate void DoSomethingUseful(); // same as Action delegate
class Program
{
/// <summary>
/// create delegate
/// </summary>
/// <param name="namespace"> namespace name </param>
/// <param name="class"> class name </param>
/// <param name="method"> method name </param>
/// <returns></returns>
public static DoSomethingUseful GetDelegate(string #namespace, string #class, string method)
{
// common argument checks
if (#namespace == null) throw new ArgumentNullException("namespace");
if (#class == null) throw new ArgumentNullException("class");
if (method == null) throw new ArgumentNullException("method");
// find class
Type type = Type.GetType(#namespace + "." + #class);
if (type == null) throw new Exception("type not found");
// find method
MethodInfo methodInfo = type.GetMethod(method);
if (methodInfo == null) throw new Exception("method not found");
// create the delegate
return (DoSomethingUseful)Delegate.CreateDelegate(typeof(DoSomethingUseful), methodInfo.IsStatic ? null : Activator.CreateInstance(type), methodInfo);
}
static void Main(string[] args)
{
// creating delegates
DoSomethingUseful methodA = GetDelegate("NamespaceA", "ClassAB", "MyMethod");
DoSomethingUseful methodB = GetDelegate("NamespaceA", "ClassAB", "MyStaticMethod");
// usage
methodA();
methodB();
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
Complete code sample below.
Remember, that you should create class instance, if your class method is not static (object instance = Activator.CreateInstance(type););
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestConsole.Data;
namespace NamespaceA
{
public class ClassAB
{
public void MyMethod()
{
Console.WriteLine("You invoke NamespaceA.ClassAB.MyMethod");
}
public static void MyStaticMethod()
{
Console.WriteLine("You invoke NamespaceA.ClassAB.MyStaticMethod");
}
}
}
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Type type = Type.GetType("NamespaceA.ClassAB");
object instance = Activator.CreateInstance(type);
type.GetMethod("MyMethod").Invoke(instance, null); // instance is required
type.GetMethod("MyStaticMethod").Invoke(null, null); // instance is not required
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
use static.
public static HelperClass
{
public static void HelperMethod() {
// ...
}
}
Usage (after adding a reference to your Class Library).
HelperClass.HelperMethod();

Get field values from class within class

This has been driving me mad for a while now. I have a class which contains other classes. I need to loop through the first class looking for typeof second class then retreive the value of the fields.
the below code obviously fails on the line
Console.WriteLine(field.GetValue(mFC.field.secondClassString));
as this isn't a valid field. Possibly I'm going about this the wrong way - any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
MyFirstClass mFC = new MyFirstClass();
FieldInfo[] fI = mFC.GetType().GetFields();
foreach (FieldInfo field in fI)
{
if (field.FieldType.Name == "MySecondClass")
{
//get the fields
Console.WriteLine(field.GetValue(mFC.field.secondClassString));
}
}
}
}
class MyFirstClass
{
public MySecondClass firstMSC = new MySecondClass("First Instance");
public MySecondClass secondMSC = new MySecondClass("Second Instance");
public string firstClassString = "I'm from the first class";
public int firstClassInt = 5;
}
class MySecondClass
{
public MySecondClass(string input)
{
this.secondClassString = input;
}
public string secondClassString;
public int secondClassInt = 10;
}
}
field.GetValue accepts the instance from which it gets the field value.
In your case I would expect it should be field.GetValue(mFC).
Also field.FieldType.Name == "MySecondClass" is not the best way to check the type as type name change will cause code to break. I recommend replacing it with field.FieldType == typeof(MySecondClass).
((MySecondClass)field.GetValue(mFC)).secondClassString;
use this inside console.writeline

Categories

Resources