Create definition to integer - c#

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;
}
}

Related

Unable to Access Extension Method in Main Method

I am using extension method to convert string to integer. But i am not able to access extension method in main method. What was i did wrong. My Code is below
public static class ConvertIntExtensionMethod
{
public static int ConvertToInt(this int str) {
int value;
value = Convert.ToInt32(str);
return value;
}
}
static void Main(string[] args)
{
string str = "100";
//int i = 10;
//bool result = i.IsGreaterThan(100);
int result = str.ConvertIntExtensionMethod(); //Here is the problem
Console.WriteLine(result);
Console.ReadLine();
}
please try to help me thank you...
Extension methods must be defined in a top level static class, it seems that your ConvertIntExtensionMethod class is a nested class
If you want to add this method to string, the type of the param must be this string
Call str.ConvertToInt() instead of str.ConvertIntExtensionMethod()
str does not contain any member known as ConvertIntExtensionMethod(). You need to do this:
public static class ConvertIntExtensionMethod
{
public static int ConvertToInt(this string str)
{
int value;
value = Convert.ToInt32(str);
return value;
}
}
class Program
{
static void Main(string[] args)
{
string str = "5";
//int i = 10;
//bool result = i.IsGreaterThan(100);
int result = ConvertIntExtensionMethod.ConvertToInt(str); //Here is the problem
Console.WriteLine(result);
Console.ReadLine();
}
}
It will convert an integer as a string to an int.
I am give the wrong parameter type in the extension method. Main method passing string value but extension method parameter is integer. This is the problem what i found.
Updated code in Extension method is given below
public static int ConvertToInt(this string str)
{
int value;
value = Convert.ToInt32(str);
return value;
}

How to call a class method from another class instance

I'm new to C#, I'm in doubt about how to make this work:
namespace Core {
public class A{
private reandonly string _var;
public A(string var){
_var=var
}
public GetValue() => return _var;
}
}
using System;
namespace Core.Resources {
public static class B{
public static void DoSomething(){
Console.Writeline($"{A.GetValue()}");
}
}
}
public class C{
static void Main(string args[]){
A a = new A("name");
a.Resources.B.DoSomething();
}
}
A is in main folder, B is in Main/Resources folder, together they make a classlib, Program.cs is using this lib. Is there a way to make this work?
If you write a.Resources you are basically trying to retrieve the member Resources of the class A, which is obviously not defined. Since B is a static class defined in the Core.Resources namespace, all you have to do is to change your code as follows:
public class C
{
public static void Main(string args[])
{
A a = new A("A");
Core.Resources.B.DoSomething();
}
}
or, alternatively, if you don't want to reference the namespace every time:
using Core.Resources;
public class C
{
public static void Main(string args[])
{
A a = new A("A");
B.DoSomething();
}
}
Note that if yuu explicitly define a public constructor for A that accepts one or more arguments, the default parameterless constructor is no more available... hence you have to pass a string to the A constructor if you don't want to see an error in your console. Alternatively, you have to rewrite your A class so that it implements a default parameterless compiler, for example:
public class A
{
private reandonly String _var;
public A() : this(String.Empty) { }
public A(String var)
{
_var = var;
}
}
EDIT AS PER OP COMMENTS AND QUESTION CHANGES
public class A
{
private reandonly String _var;
public String Var
{
get { return _var; }
}
public A(String var)
{
_var = var;
}
}
public static class B
{
public static void DoSomething(String text)
{
Console.Writeline(text);
}
}
public class C
{
public static void Main(string args[])
{
A a = new A("name");
B.DoSomething(a.Var);
}
}

Iteration through properties with custom attributes in a class

I've got a class like this with some custom attributes. I'm not sure whether i actually have to implement these.
[AttributeUsage(AttributeTargets.Field)]
private class IsValue : Attribute { }
[AttributeUsage(AttributeTargets.Field)]
private class IsRep : Attribute { }
[AttributeUsage(AttributeTargets.Class)]
private class IsConstant : Attribute { }
public static class Constants
{
[IsConstant]
public static class EulerGamma
{
[IsValue]
public const double Value = 0.5772156649015;
[IsRep]
public const string Str = "γ";
}
[IsConstant]
public static class EulerNumber
{
[IsValue]
public const double Value = 2.718281828459;
[IsRep]
public const string Str = "e";
}
[IsConstant]
public static class Pi
{
[IsValue]
public const double Value = 3.1415926535898;
[IsRep]
public const string Str = "π";
}
[IsConstant]
public static class GoldenRatio
{
[IsValue]
public const double Value = 1.6180339887499;
[IsRep]
public const string Str = "φ";
}
}
Let's say this is in some class "MyMathClass", where I'd like to implement a method like this:
string ValueOrString(double x)
This method would return string representation of the constant if the number passed is equal to the constant, else it would return the original number.
So, if i passed exactly 3.1415926535898 this method would give me the string "π".
If is passed for example 2.5315621321 this would return me "2.5315621321" (string).
Would you please help me out?
I would create a class that uses a dictionary:
public static class Constants
{
static Dictionary<double, string> constantNames;
static Constants()
{
Constants.constantNames = new Dictionary<double, string>();
Constants.constantNames.Add(3.1415926535898, "π");
Constants.constantNames.Add(2.718281828459, "e");
}
public static string ValueOrString(double value)
{
if (constantNames.ContainsKey(value))
{
return constantNames[value];
}
else
{
return value.ToString();
}
}
}
When the function string ValueOrString(double value) is called, you can check if the provided value exists in the dictionary. If it exists, you retrieve the name of the constant from it. Otherwise, you return the value as a string.

Call constructor with other class constant value

I want a constructor call to only allow a limited range of "extensions". Let's say I have these 2 classes:
public class Foo
{
public Foo(Extension ext)
{
// do something
}
}
public class Extension
{
public const string TXT = ".txt";
public const string XML = ".xml";
}
So, when another developer would want to use Foo he can only do so with the values from the Extension class like so:
Foo foo = new Foo(Extension.TXT);
But when trying to do this I get an IDE error saying: "cannot convert from 'string' to '<ProjectName>.Extension'.
As a "workaround" I could change my Extension class to something like this:
public class Extension
{
public enum File
{
TXT,
XML
}
}
and use it like this:
Foo foo = new Foo(Extension.File.TXT);
which works perfectly fine but what I do not like is that the call is one level longer (class -> enum -> element instead of class -> element).
So, the questions is is my workaround actually the only valid, correct or best practice solution?
You can use a Java style enum class
public class Extension
{
string _Extension = null;
private Extension(string ext)
{
_Extension = ext;
}
public static Extension TXT
{
get { return new Extension(".txt"); }
}
public static Extension XML
{
get { return new Extension(".xml"); }
}
public override string ToString()
{
return _Extension;
}
public override bool Equals(object obj)
{
var e = obj as Extension;
if (e == null) return false;
return e._Extension == this._Extension;
}
public override int GetHashCode()
{
return _Extension.GetHashCode();
}
}
The first example has Extension being used as a class with a couple of string constants. The second example uses an enum in lieu of the constants.
public class Foo
{
// this .ctor expects a type of Extension, not a string.
public Foo(Extension ext)
{
// do something
}
}
// This class has only constant string values.
public class Extension
{
public const string TXT = ".txt";
public const string XML = ".xml";
}
Attempting to pass in a string to the above .ctor will not work as it is expecting a type of Extension, not a string.
// this passes in a string, not a type.
Foo foo = new Foo(Extension.TXT);
As you are wanting to limit the values available to the Foo .ctor, then use an enum as you have in your 2nd example:
public class Foo
{
public Foo(File ext)
{
// do something
}
}
public enum File
{
TXT,
XML
}
Then this will work as expected:
Foo foo = new Foo(File.TXT);
Why not to declare enum outside of class Foo and without any special class like extension?
public enum Extension
{
TXT,
XML
}
public class Foo
{
public Foo(Extension ext)
{
// do something
}
}
Then when you are constructing a Foo object you can simply do:
Foo foo = new Foo(Extension.TXT);
You could define a default constructor and implicit operator for string to Extension. Eg. something like:
public class Extension
{
public const string TXT = ".txt";
public const string XML = ".xml";
private _value;
public Extension(string value){if(value == TXT || value == XML) _value = value; else throw new NotImplementedException();}
public static implicit operator string(Extension value){return _value;}
public static implicit operator Extension(string value){if(value == TXT || value == XML) _value = value; else throw new NotImplementedException();}
}
that way you could call Foo(".txt") or Foo(Extension.TXT)
or you could define TXT as an instance of Extension:
public class Extension
{
public const Extension TXT = new Extension(".txt");
public const Extension XML = new Extension(".xml");
public Value{get;private set;}
public Extension(string value){Value = value;}
}
Just change the first declaration of Extesion from Class to Enum

Custom Attribute - get value of underlying enum

I'm not sure of all of the correct terminology for what I am trying to do, so I will just dive in with some code.
Current Setup:
public enum NavigationLinks
{
[FriendlyName("System Dashboard")]
SystemDashboard,
[FriendlyName("Trading Dashboard")]
TradingDashboard,
}
public class UINameAttribute : Attribute
{
public string Value { get; private set; }
public UINameAttribute(string Value)
{
this.Value = Value;
}
}
What I would like:
public enum NavigationLinks
{
[FriendlyName]
SystemDashboard,
[FriendlyName]
TradingDashboard,
}
public class UINameAttribute : Attribute
{
public string Value { get; private set; }
public UINameAttribute(string Value)
{
this.Value = Value;
}
public UINameAttribute()
{
string AttributedValue = this.AttributedObject.ToString();
// Take the value of the attribute and add a space in between the camel case.
}
}
Can I access the underlying 'thing' that the attribute is on from within the constructor of the attribute?
No, you can't access attributed member from within the attribute's constructor.
But why do that anyway, if you already have a logic how to resolve friendly name from enum value.
public enum NavigationLinks
{
SystemDashboard,
TradingDashboard,
}
public static class Program
{
private static string ToFriendlyName(string defaultName)
{
var sb = new StringBuilder(defaultName);
for (int i = 1; i < sb.Length; ++i)
if (char.IsUpper(sb[i]))
{
sb.Insert(i, ' ');
++i;
}
return sb.ToString();
}
public static void Main(string[] args)
{
var value = NavigationLinks.SystemDashboard;
var friendlyName = ToFriendlyName(value.ToString());
}
}
In addition to Stipo's approach you can also write an extension method to get the name, something like this:
public static class NavigationLinksExtension
{
public static string GetFriendlyName(this NavigationLinks navLink)
{
string tmpName = navLink.ToString();
tmpName = Regex.Replace(tmpName, "(?<=[a-z])([A-Z])", " $1"); // insert space
return tmpName;
}
}
Then you can simply access the value:
NavigationLinks nl = NavigationLinks.TradingDashboard;
string nlFriendlyName = nl.GetFriendlyName();
An attribute can't (directly) get access to the thing it is describing. If you want ToString() to be the default and only override it occasionally, you would be better off with a helper function (e.g. GetFriendlyName) that defaults to ToString(), but replaces it with the value in a FriendlyName attribute should one exist.
Please try the following:
var inputString = NavigationLinks.SystemDashboard;
Regex.Replace(inputString, "([A-Z][a-z0-9]+)+", "$1$2");
Use the DescriptionAttribute (or create a custom attribute), then, using Reflection to get the value:
Create the class EnumDescriptions (using System.ComponentModel and System.Reflection):
public class EnumDescriptions
{
public static string StringValueOf(Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes[0].Description;
}
And put Description in the Enum:
public enum Animals
{
[Description("System Dashboard")]
SystemDashboard,
[Description("Trading Dashboard")]
TradingDashboard,
}
To get the values:
static void Main(string[] args)
{
Console.WriteLine(EnumDescriptions.StringValueOf(Animals.SystemDashboard));
Console.WriteLine();
Console.WriteLine(EnumDescriptions.StringValueOf(Animals.TradingDashboard));
Console.Read();
}

Categories