Unable to call extension method during runtime for dynamic variable - c#

Below is the sample code and it is throwing error (''string' does not contain a definition for 'ToUpperExtn'') during runtime. How can i handle this.
class Program
{
static void Main(string[] args)
{
dynamic name = "Prasad";
**Console.WriteLine(Convert.ToString(name).ToUpperExtn());** // Error: ''string' does not contain a definition for 'ToUpperExtn''
string name1 = "Prasad";
Console.WriteLine(name1.ToUpperExtn()); // Working fine
}
}
public static class StringExtensions
{
public static string ToUpperExtn(this string value)
{
return value.ToUpper();
}
}

Related

Can't access class method in a seperate method c#, the name item1 does not exist in the current context

Trying to use a class method, with an instance of that class in a separate method. Used method RandomItem() to build instance of class Item. Using ViewItem() to display the item, it says:
"The name 'item1' does not exist in this context"
This is my code:
class Program
{
public class Item
{
public string part1;
public Item(string _part1)
{
part1 = _part1;
}
public void PrintItem()
{
Console.WriteLine(part1);
}
}
public static void Main()
{
RandomItem();
ViewItem();
}
public static void RandomItem() {
string randomPart1 ="";
Item item1 = new Item(randomPart1);
}
public static void ViewItem() {
item1.PrintItem(); //this is where the error is "The name 'item1' does not exist in the current context
}
}
}
Kind of new to c#, just not sure why I can't access item1.PrintItem(), or if I'm even allowed to do this. Any help would be much appreciated.
If a variable is local, you need to return it so the caller can access it. Then you need to pass it as an argument for another method to access it.
public static void Main()
{
var item = RandomItem(); //Retrieve item
ViewItem(item); //Then pass it in
}
public static Item RandomItem() {
string randomPart1 ="";
Item item1 = new Item(randomPart1);
return item1; //Return the item to Main
}
public static void ViewItem(Item item1) { //Accept item as argument from Main
item1.PrintItem();
}
There are other options-- for example, you could use a static variable-- but this is the most common way to do it.
You need to declare "item1" outsite of your "RandomItem()" method as a member of your "Program" class.
On a console App the entry point is a static method. So everything you declare in your "Program" class must be static.
class Program
{
public static Item item1; // the static field that contains the instance of your "Item"
public class Item
{
public string part1;
public Item(string _part1)
{
part1 = _part1;
}
public void PrintItem()
{
Console.WriteLine(part1);
}
}
public static void Main()
{
RandomItem();
ViewItem();
}
public static void RandomItem() {
string randomPart1 ="";
item1 = new Item(randomPart1);
}
public static void ViewItem() {
item1.PrintItem();
}
}

Create definition to integer

I receive this kind of error:
int does not contain a definition for 'childConvert' and no accessible extension method 'childconver' accepting a first argument of type'int' could be found (are you missing assembly reference)
In Main Method:
int n = 10;
string Name = n.ChildConver();
In Child Method:
public static string ChildConver(this int Name)
{
string Namecovert = Convert.ToString(Name) + "Convertion";
return Namecovert;
}
Try to put it in a static class.
public static class Common
{
public static string ChildConver(this int name)
{
return name + "Convertion";
}
}
Extension methods must be defined in a non-generic static class.
Ref: MSDN
Define extension method in separate class.
public static class IntHelper
{
public static string ChildConver(this int Name)
{
string Namecovert = Convert.ToString(Name) + "Convertion";
return Namecovert;
}
}
public static string ChildConver(this int Name)
{
retunt Name + "Convertion";
}
Try ToString()
public class Program
{
public static void Main()
{
int n = 10;
string Name = n.ChildConver();
System.Console.WriteLine(Name);
}
}
public static class Ext
{
public static string ChildConver(this int Name)
{
string Namecovert = Name.ToString() + " Convertion";
return Namecovert;
}
}

How to use an interface within a public interface with a main?

//Program.cs
public interface TestVal
{
//Input Param
string Input { get; }
//will return output
TestValRes ValidateRe(string input);
}
class MyClass : ITestVal
{
static void Main(string[] args)
{
var instance = new MyClass();
instance.Run();
}
public void Run()
{
ValidateRe("test");
}
public ITestValRes ValidateRe(string input)
{
return null; // return an instance of a class implementing ITestValRes here.
}
}
//TestvalRes.cs
public interface TestvalRes
{
string Input { get; }
bool IsValid { get; }
}
So I just want to pass a string to the TestVal, do validation and call TestvalRes to return whether it is Valid or not, and if Invalid, why? So the validation will be done in the first public interface - TestVal, however I still need to call it inside the Main(), right?
First off, I'd recommend following C# naming conventions and name your interfaces ITestVal and ITestValRes respectively.
Next, static method cannot call instance methods in the same class (without creating an instance and using that). You need to create an instance of the class and pass control of the application flow to that:
class MyClass : ITestVal
{
static void Main(string[] args)
{
var instance = new MyClass();
instance.Run();
}
public void Run()
{
ValidateRe("test");
}
public ITestValRes ValidateRe(string input)
{
return null; // return an instance of a class implementing ITestValRes here.
}
}

Getting class and method names at runtime

How to get the name of the class and the name of the method of this class at runtime. The code gets compiled and then obfuscated using some open source obfuscator. Here is an example:
class MainClass {
public static void Main(string[] args) {
Console.WriteLine(nameof(Test));
Console.WriteLine(nameof(Test.TestMethod));
Console.ReadLine();
}
}
class Test {
public static void TestMethod() {
Console.WriteLine("Hello World!");
}
}
The obfuscator renames classes and methods like this:
MainClass -> A
MainClass.Main -> A.a
Test -> B
Test.TestMethod -> B.a
When I run my code after compilation and obfuscation I get:
B
TestMethod
So the nameof works as expected for the class name, but doesn't work for the method name. How does the nameof work? What is the correct way to get the obfuscated names of the class and the method at runtime?
Use the following:
class MainClass {
public static void Main(string[] args) {
var methodinfo = typeof(Test).GetMethod("TestMethod");
var handle = methodinfo.MetaDataToken;
MethodBase method = System.Reflection.MethodBase.GetMethodFromHandle(handle);
string methodName = method.Name;
string className = method.ReflectedType.Name;
string fullMethodName = className + "." + methodName;
Console.WriteLine(fullMethodName);
Console.ReadLine();
}
}
class Test {
public static void TestMethod() {
Console.WriteLine("Hello World!");
}
}

Why doesn't this trigger an "Ambiguous Reference Error"?

public class A
{
public virtual string Go(string str) { return str; }
}
public class B : A
{
public override string Go(string str) {return base.Go(str);}
public string Go(IList<string> list) {return "list";}
}
public static void Main(string[] args)
{
var ob = new B();
Console.WriteLine(ob.Go(null));
}
http://dotnetpad.net/ViewPaste/s6VZDImprk2_CqulFcDJ1A
If I run this program I get "list" sent out to the output. Why doesn't this trigger an ambiguous reference error in the compiler?
Since the overload taking a string is not defined in B (only overriden), it has lower precedence than the one taking an IList<string>.
Therefore, the second overload wins and there's no ambiguity.
This is explained in detail in http://csharpindepth.com/Articles/General/Overloading.aspx

Categories