how can I create ToInt32 method in System namespace? - c#

As you know, we can convert to string using Convert.ToString or ToString. I want to make the same thing for integer, byte etc. Furthermore, I want to see this method for every object when I put dot.
How should I write the method?

You are looking for a extension method. just create a static class and a static method inside it like:
public static class Exts
{
public static int ToInt32(this string x)
{
int result = 0;
int.TryParse(x, out result);
return result;
}
}
of course my method is a sample and it just returns 0 for any string value that is not castable to int, however you may write any code, accept default value as argument, throw exception,...
Then you can use it like:
string a = "123";
int b = a.ToInt32();
int c = "321".ToInt32();

Write a generic extension that converts any type to Int32:
public static class ObjectExt {
public static int ToInt<T>(this T obj) => Convert.ToInt32(obj);
}

Related

is ToInt32() an extension method in C#? specially Convert.ToInt32()

does ToInt32() is extension method in C#? specially Convert.ToInt32()
No. An extension method's raison d'être is to allow the instance method invocation syntax to be used for methods declared outside the type. You'll find that you cannot do that with any of the Convert.ToInt32 methods.
For example, the type String does not have a ToInt32(String) member method. If you wanted to convert a String to an Int32, you could write a static method like this:
public static class StringConverters
{
public static Int32 ToInt32(String number)
{
return Int32.Parse(
number,
NumberStyles.Integer,
CultureInfo.CurrentCulture.NumberFormat);
}
}
And call it like this:
var n = StringConverters.ToInt32("12345");
or, (in some cases this would be acceptable)
using static StringConverters;
…
var n = ToInt32("12345");
But, if you want to call with the instance method invocation syntax, you would create an extension method as static method with first parameter this in a non-generic, non-nested, static class:
public static class StringConverters
{
public static Int32 ToInt32(this String number)
{
return Int32.Parse(
number,
NumberStyles.Integer,
CultureInfo.CurrentCulture.NumberFormat);
}
}
And call it like this:
var n = "12345".ToInt32();
The String type still does does not have a ToInt32(String) member. It just appears that the ToInt32 declaration has extended that type. That's why it is called an extension method.
Convert.ToInt32() is not an extension method, it is a static method inside the static class Convert.
However, you can create an extension method to do that like this:
public static class MyExtensions
{
public static Int32 ToInt32(this object obj)
{
return Convert.ToInt32(obj);
}
}
Usage:
object obj = 5;
int five = obj.ToInt32();
You can press F12 on ToInt32() and you can see
namespace System
{
public static class Convert
{
public static int ToInt32(object value);
}
}
So not a extension but static
The extension in C# in something like below
public static int MethodName(this String str)
{
...
}

C# Operator Overloading, rewriting string?

I'm very fresh to C#
Currently learning Operator overloading
i'm trying to do something like this:
string val = 500; (I can't implicitly)
and then
Number n1 = val;
I manages to get the Number n1 = someintvalue, for instance:
Number n1 = 500;
like this:
public struct Number
{
public int Value { get; set; }
public Number(int Val)
{
Value = Val;
}
public static implicit operator Number(int num)
{
return new Number(num);
}
}
However, when trying to make Number n1 = val; (when val is a string)
I simply cant since the first line cant compile:
string val = 500;
and the following wont work:
public static implicit operator string(int A)
{
return new string(A);
}
because of 1 error which i can not understand
1)User-defined conversion must convert to or from the enclosing type
by the way i get the idea of op overload
underthis specific case of: return new Number(num);
I simply init the ctor
still need some more fundemental understanding
thx ahead!
I presume the function you quote is within the Number class. You have added a conversion operator from an int to a string within that class, which is not legal. You can only add operators that convert to or from the type they're defined in, such as:
public static implicit operator string(Number A)
{
return new string(A.Value);
}
which will fail because string does not have a constructor that takes an int. You could do:
public static implicit operator string(Number A)
{
return A.ToString();
}
But the standard way to "convert" to a string is to overload the ToString method, which the compiler often calls automatically when a conversion to string is requested:
public override string ToString()
{
return Value.ToString();
}

Why is this not legal in C#?

This doesn't work
public class Foo {
private int X { get; }
public Foo(string s) {
int.TryParse(s, out X);
}
}
but this works:
public class Foo {
private int X { get; }
public Foo(string s) {
int x;
int.TryParse(s, out x);
X = x;
}
}
What is the difference between the two, since the out parameter doesn't need to be initialised. Why the property cannot be passed as an out parameter?
I assume this is C# 6.0 because you have a get-only property.
It doesn't work because properties cannot be passed by reference. A function that takes a ref int or an out int parameter in C# is like a function that takes an int& in C++.
But an int property is not just an int at some address. A property can run any code it wants to in both the get and the set. And the language should not treat an auto-implemented property as special.
What if I wrote code like the following?
public class Foo {
private int X {
get { return 0; }
set { }
}
public Foo(string s) {
int.TryParse(s, out X);
}
}
There simply isn't any address of an int to pass into TryParse. The rules for whether the code is allowable are not permitted to look inside the get and set implementations.
Note that this works fine:
public class Foo {
private int X;
public Foo(string s) {
int.TryParse(s, out X);
}
}
When you use out, under the hood it's really a memory address that gets passed to the function that you call. A property is not a variable but a function and you cannot take its address so a property cannot be passed in place of an out parameter.
A member variable (or local variable) occupies memory and the compiler can take their address and pass it so it works with variables but not with properties.

Extension methods with type name as `this` parameter, e.g. int?.TryParse(“32”)

I want to write an extension method for nullable int so that I could write the code int?.TryParse(“32”) in a similar manner to writing int.TryParse(“32”). The following method signature is not valid:
public static int? TryParse(this Type(int?), string input)
{
...
}
Is there any solution?
public static int? TryParse(this string input) {
int i;
return int.TryParse(input, out i) ? i : (int?)null;
}
Usage:
var i = yourString.TryParse();
I think you may want to define a generic method like this:
public static T? TryParse<T>(this string input) where T : struct {
T i = default(T);
object[] args = new object[] { input, i };
var tryParse = typeof(T).GetMethod("TryParse",
new[] { typeof(string), typeof(T).MakeByRefType() });
if(tryParse != null){
var r = (bool) tryParse.Invoke(null, args);
return r ? (T) args[1] : (T?)null;
}
return (T?)null;
}
//Usage
double? d = yourString.TryParse<double>();
int? i = yourString.TryParse<int>();
Using the generic method above is very convenient but the performance may be reduced a little due to using reflection. If you just want some TryParse methods for some types int, double, ... You should define particular method for each one, named them differently like TryParseInt, TryParseDouble, TryParseDecimal, ... and apply the similar code to the first code snippet I posted above.
Extension methods look like instance methods, but are in fact static methods. When you define an extension method, you can extend instances of a class with a new method, but you cannot extend the class itself with a new static method.

Method should return multiple values

Hii
I have method in C#, I have to return multiple values from that method with out using collections like arrays. Is there any reliable way ?
Yes, the out keyword:
public void ReturnManyInts(out int int1, out int int2, out int int3)
{
int1 = 10;
int2 = 20;
int3 = 30;
}
then call it like this:
int i1, i2, i3;
ReturnManyInts(out i1, out i2, out i3);
Console.WriteLine(i1);
Console.WriteLine(i2);
Console.WriteLine(i3);
which outputs:
10
20
30
EDIT:
I'm seeing that a lot of posts are suggesting to create your own class for this. This is not necessary as .net provides you with a class to do what they are saying already. The Tuple class.
public Tuple<int, string, char> ReturnMany()
{
return new Tuple<int, string, char>(1, "some string", 'B');
}
then you can retrieve it like so:
var myTuple = ReturnMany();
myTuple.Item1 ...
myTuple.Item2 ...
there are generic overloads so you can have up to 8 unique types in your tuple.
Well, you could use:
a custom class/struct/type, containing all your values
out parameters
I.e.:
class MyValues
{
public string Val1 { get; set; }
public int Val2 {get; set; }
}
public MyValues ReturnMyValues();
or
public void ReturnMyValues(out string Val1, out int Val2);
If you are using .NET 4.0 you can use one of the generic Tuple classes to return multiple values from a method call. The static Tuple class provides methods to create Tuple objects. So you do not have to define your own return type for the method.
public Tuple<string,int> Execute()
{
return new Tuple<string,int>("Hello World", 2);
}
Yes could create a new type that will contain multiple properties and then return this type:
public MyType MyMethod()
{
return new MyType
{
Prop1 = "foo",
Prop2 = "bar"
};
}
Why should using 'out' being an unreliable way? (Or did you make a typo and meant without?)
There are several methods:
Return a object which holds multiple
values (struct/class etc)
out
ref
A Descriptor class, or structure. You must put it somewhere as it's logical that a method must return only one value. Alternatively you can use out or ref, but i would go returning a class.
Btw what's holding you not to use collections?.
public int Method Name(out string stringValue, out int intValue)
{
///
Method goes here
///
return intVaraible
}
here you will get 3 return Values
1. stringValue
2. intValue
3. intVariable

Categories

Resources