L
L
LiptonOlolo2016-04-29 05:03:26
C++ / C#
LiptonOlolo, 2016-04-29 05:03:26

How to limit expansion?

Good morning.
There is an extension for all data types

public static Int32 ToInt32(this Object line)
{
  return Convert.ToInt32(line);
}

But I would like it to appear on types like String, Int, Double, etc., how can I do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2016-04-29
@lexxpavlov

This cannot be done, unfortunately.
I propose to make several similar methods in one class, one for each required type:

public class NumericExtensions
{
  public static Int32 ToInt32(this Double line)
  {
    return (Int32)line;
  }
  public static Int32 ToInt32(this float line)
  {
    return (Int32)line;
  }
  public static Int32 ToInt32(this String line)
  {
    var res;
    int.TryParse(line, out res);
    return res;
  }
  // ... для каждого нужного типа
}

M
Michael, 2016-04-29
@Sing303

You are expanding the base object, there is no way to do it. Only by creating different methods for the desired objects

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question