Ambiguous call functions in the class - c#

How to get around? I do not want to have functions with different names.
public class DataRowSafe
{
public String Get(String Column)
{
return String.Empty;
}
public int Get(String Column)
{
return 0;
}
}
DataRowSafe r=new DataRowSafe();
String res=r.Get("Column1");
int res2=r.Get("Column2");//<--- Ambiguous call

The overloading of methods requires your similar-named methods to have different signatures. The return-value is insignificant! Have a look at this tutorial here.

You can't, there is no way, the only way would be to have a different signature.

You can you referenced parameners like this instead
public class DataRowSafe
{
public void Get(String Column, ref string myParam)
{
myParam = String.Empty;
}
public void Get(String Column,ref int myParam)
{
myParam = 0;
}
}
int i = 0;
string st = "";
new DataRowSafe().Get("name", ref i);
new DataRowSafe().Get("name", ref st);

you should be getting an error like
'DataRowSafe' already defines a member called 'Get' with the same
parameter types
The return type of the function is not significant but in this case the compiler is confused with the two method available for call and not sure which is to be picked up maybe you could use generics to overcome this
a sample like
public static T GetValue<T>(string column)
{
string returnvalue="";
//process the data ...
return (T)Convert.ChangeType(returnvalue, typeof(T), CultureInfo.InvariantCulture);
}

It is not possible, because overloading works only for different signatures. If signatures are the same then c# compiler will return error.

Related

Methods in c# enums

In Java we can use methods in enums, for example i can write
public static void main(String []args){
System.out.println(GetNum.TWO.get());
}
enum GetNum{
ONE{
public int get(){
return 1;
}
},
TWO{
public int get(){
return 2;
}
};
public abstract int get();
}
maybe somebody can say me: in c# enums can I do something like this?
Not really, but you can sort of though the use of extension methods.
Given an enumeration such as
enum HurfDurf
{
Hurr,
Durr
}
you can create an extension method such as
static class HurfDurfExtensions
{
public static string Wat(this HurfDurf lol)
{
return lol == HurfDurf.Hurr ? "Wew lad" : "eyy boss";
}
}
and use it like
var whatisthisidonteven = HurfDurf.Hurr.Wat();
No you can't. In the background enum are value-types (e.g. just an int).
E.g. you can do int i = (int)yourEnum;and vice versa.

Is it possible to change the parameters that a predefined method can take in C#?

Im not sure if this is possible. Im using a method that takes the parameter int but i found myself in a situation where i need to be able to use a float value. Does anyone know if there is anyway to change the parameters that a predefined method can take?
Thanks All
Best
Alex
You can overload a method as follows:
public static float myMethod(float sumNumber)
{
// whatever you need for code here
return sumNumber;
}
public static int myMethod(int sumNumber)
{
// whatever you need for code here
return sumNumber;
}
C# has generics for his type of requirement, where you want to apply a logic indifferent of the type of parameter input
for example :
T foo<T>(T param)
{
return param + 1;
}
//and it can be used like this
int i;
foo<int>(i); // return type is int
float f;
foo<float>(f); // return type is float
Member overloading means creating two or more members on the same type that differ only in the number or type of parameters but have the same name. - Microsoft MSDN
// your method
public static double Inc(int i)
{
return i + 1;
}
// your method (overloaded)
public static double Inc(double d)
{
return d + 1;
}
int i = Inc(3);
double d = Inc(2.0); // You can use the same method with different parameter types
The website www.dotnetperls.com has a lot of nice examples. If you want to see another explanation besides MSDN, you may read this.
You can define a generic class for such methods.
public class GenericMethodsClass<T>
{
public static T myMethod(T sumNumber)
{
// whatever you need for code here
return sumNumber;
}
}
Calling:
GenericMethodsClass<int>.myMethod(1);
GenericMethodsClass<double>.myMethod(1.2);

passing SqlDataReader to function as parameter for casting

for casting data of SqlDataReader I do these (example for common data types):
string name = reader["name"].ToString(); //for string
int i = 0; i = int.TryParse(reader["i"].ToString(), out i); //for int
int i = reader.GetInt32(reader.GetOrdinal("i")); //or this again for int
bool b = reader.GetBoolean(reader.GetOrdinal("b")); // for boolean
I want to create a class with these functions:
public static class gd{
public static bool Bool(SqlDataReader rd, string name)
{
return rd.GetBoolean(rd.GetOrdinal(name));
}
public static int Int(SqlDataReader rd, string name)
{
int i=0;
i = int.TryParse(reader["i"].ToString(), out i);
return i;
}
}
and then just use:
int i=c.Int(reader,"i");
bool b=c.Bool(reader,"b");
DateTime dt = c.Date(reader,"dt");
I want to know is it a good idea to pass datareader as parameter? anyone has got a better Idea for casting datareader data?
Yes, it's OK to pass DataReader as parameter (as any other reference type). When you are passing reader, only reference to it is passed to another method. And it's OK to use methods to make your code more readable and maintainable.
You can write extension method in order to simplify your code:
public static class Extensions
{
public static bool GetBoolean(this IDataReader reader, string name)
{
return reader.GetBoolean(reader.GetOrdinal(name));
}
public static int GetInt32(this IDataReader reader, string name)
{
return reader.GetInt32(reader.GetOrdinal(name));
}
}
Usage will look like:
int i = reader.GetInt32("i");
bool b = reader.GetBoolean("b");
Your idea seems fine (passing reference to SqlDataReader doesn't lag application) if you wish to handle exceptions internally. You could use methods provided by SqlDataReader class specifically for getting data in desired formats:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
Check if those methods are sufficent for you. If not, your static helper class seems okay, but I'd advise you to avoid duplicating functionality that's already implemented inside SqlDataReader, because what's the point of reinventing the wheel?

Is possible return more than one return type in a Method?

I use asp.net 4 and c#.
I would like to know if could be possible return more than one return type in a Method.
As example in this method I return only a single bool type.
protected bool IsFilePresent()
{
return File.Exists(Server.MapPath("/myFile.txt"));
}
But lets imagine I would like return also a string type using in the same method like:
string lineBase = File.ReadAllText(Server.MapPath("/myFile.txt"));
Is possible to do it?
I would appreciate some code example. Many Thanks.
No, it's not possible to return multiple, different values. You have a few alternatives:
One is to make a class or struct that has each of the things you want to return as properties or fields.
Another is to use out parameters, where you pass in a variable to a method, which the method then assigns a value to.
You could also use ref parameters (pass by reference), which is similar to out, but the variable you pass in needs to have been assigned before you call the method (i.e. the method changes the value).
In your case, as cjk points out, you could just have the method return a string with the file contents, or null to indicate that the file didn't exist.
For this example, you have 3 choices.
Add an out parameter to your method and set it in the body (code below)
Create a custom class that contains a Booelan and a String and return that
Just return the string, but return null when the file does not exist
protected bool IsFilePresent(out String allText)
{
Boolean fileExists = File.Exists(Server.MapPath("/myFile.txt"));
if (fileExists)
{
allText = File.ReadAllText(Server.MapPath("/myFile.txt"));
}
return fileExists;
}
Yes you can only if your using framework 4. Look into tuple
http://sankarsan.wordpress.com/2009/11/29/tuple-in-c-4-0/
No, you could use out parameter instead.
http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx
http://msdn.microsoft.com/en-us/library/aa645764(v=vs.71).aspx
You can return a class with different types in it :
class TestFile
{
private bool isFilePresent;
private string lineBase;
}
Yes, you can create a wrapper class called (for instance) "Pair" parametrized with two types, put two values in the object of that class and return it as a result. In your case it would be something like Pair
I'm not a C# programmer, so I won't give you exact code.
You might want to use out-parameters.
protected bool IsFilePresent(out string fileContents) {
string filePath = Server.MapPath("/myFile.txt");
try {
fileContents = File.ReadAllText(filePath);
return true;
} catch {
fileContents = null;
return false;
}
}
You have two options.
First one, more C-ish: out parameters:
void test(out bool p1, out bool p2) {
p1 = true;
p2 = false;
}
Second one, more OO, use a struct or class to contain your results:
class Result {
public bool Part1 {get;set;}
public bool Part2 {get;set;}
}
Result test() {
return new Result {Part1 = true, Part2 = false};
}
In C# 4 you can use the Tuple class instead of creating your own result class.
I did not look at your specific requirement but you can combine the methods if you need, but keep in mind that the out parameters are discouraged in object oriented programming at least as per microsoft guidelines.
Yes you can use output parameters.
public bool GetData(string filename, out string data)
{
if (File.Exists(filename))
{
data = File.ReadAllText(filename);
return true;
}
data = string.Empty;
return false;
}
string data;
if (GetData(Server.MapPath("/myFile.txt"), out data))
{
// do something with data
}
Yes, we can. dotNet 4 support dynamic type, so you can return more than one type
public dynamic GetSomething()
{
if (!File.Exists(Server.MapPath("/myFile.txt")))
return false;
else
return File.ReadAllText(Server.MapPath("/myFile.txt"));
}
var result = GetSomething();
if(result is bool && result == false)
{
//doSomething();
}
This way is hard to read your code.
It's very easy nowadays... use Tuple
public (string,int) MyMethod(){
return ("text", 3);
}
string text;
int number;
(text, number) = MyMethod();
//OR
(var text, var number) = MyMethod();

Is it possible for a function to return two values?

Is it possible for a function to return two values?
Array is possible if the two values are both the same type, but how do you return two different type values?
Can a function return 2 separate values? No, a function in C# can only return a single value.
It is possible though to use other concepts to return 2 values. The first that comes to mind is using a wrapping type such as a Tuple<T1,T2>.
Tuple<int,string> GetValues() {
return Tuple.Create(42,"foo");
}
The Tuple<T1,T2> type is only available in 4.0 and higher. If you are using an earlier version of the framework you can either create your own type or use KeyValuePair<TKey,TValue>.
KeyValuePair<int,string> GetValues() {
return new KeyValuePair<int,sting>(42,"foo");
}
Another method is to use an out parameter (I would highly recomend the tuple approach though).
int GetValues(out string param1) {
param1 = "foo";
return 42;
}
In a word, no.
But you can define a struct (or class, for that matter) for this:
struct TwoParameters {
public double Parameter1 { get; private set; }
public double Parameter2 { get; private set; }
public TwoParameters(double param1, double param2) {
Parameter1 = param1;
Parameter2 = param2;
}
}
This of course is way too specific to a single problem. A more flexible approach would be to define a generic struct like Tuple<T1, T2> (as JaredPar suggested):
struct Tuple<T1, T2> {
public T1 Property1 { get; private set; }
public T2 Property2 { get; private set; }
public Tuple(T1 prop1, T2 prop2) {
Property1 = prop1;
Property2 = prop2;
}
}
(Note that something very much like the above is actually a part of .NET in 4.0 and higher, apparently.)
Then you might have some method that looks like this:
public Tuple<double, int> GetPriceAndVolume() {
double price;
int volume;
// calculate price and volume
return new Tuple<double, int>(price, volume);
}
And code like this:
var priceAndVolume = GetPriceAndVolume();
double price = priceAndVolume.Property1;
int volume = priceAndVolume.Property2;
It is not directly possible. You need to return a single parameter that wraps the two parameters, or use out parameters:
object Method(out object secondResult)
{
//...
Or:
KeyValuePair<object,object> Method()
{
// ..
All of the possible solutions miss one major point; why do you want to return two values from a method? The way I see it, there are two possible cases; a) you are returning two values that really should be encapsulated in one object (e.g. height and width of something, so you should return an object that represents that something) or b) this is a code smell and you really need to think about why the method is returning two values (e.g. the method is really doing two things).
with C# 7, you can now return a ValueTuple:
static (bool success, string value) GetValue(string key)
{
if (!_dic.TryGetValue(key, out string v)) return (false, null);
return (true, v); // this is a ValueType literal
}
static void Main(string[] args)
{
var (s, v) = GetValue("foo"); // (s, v) desconstructs the returned tuple
if (s) Console.WriteLine($"foo: {v}");
}
ValueTuple is a value-type, which makes it a great choice for a return value compared with a reference-type Tuple - no object needs to be garbage-collected.
Also, note that you can give a name to the values returned. It is really nice.
For that reason alone I wish it was possible to declare a ValueTuple with only one element. Alas, it is not allowed:
static (string error) Foo()
{
// ... does not work: ValueTuple must contain at least two elements
}
Not directly. Your options are either to return some kind of custom struct or class with multiple properties, use KeyValuePair if you simply want to return two values, or use out parameters.
You have basically (at least) two options, either you make an out parameter in addition to the return value of the function, something like T1 Function(out T2 second) or you make your own class putting these two types together, something like a Pair<T1,T2>. I personally prefer the second way but it's your choice.
In C# you can return more than one value using an out parameter. See example in the TryParse method of Int32 struct. It returns bool and an integer in an out parameter.
no but you can use an out parameter
int whatitis;
string stuff = DoStuff(5, out whatitis);
public string DoStuff(int inParam, out int outParam)
{
outParam = inParam + 10;
return "donestuff";
}
It is not possible to return more than one value from a function, unless you are returning a type that contains multiple values in it (Struct, Dictionary, etc). The only other way would be to use the "out" or "ref" keywords on the incoming parameters.
You could use the out parameter.
int maxAge;
int minAge;
public int GetMaxAgeAndMinAge(out int maxAge, out int minAge)
{
MaxAge = 60;
MinAge = 0;
return 1; //irrelevant for this example since we care about the values we pass in
}
I really tend to stay away from this, I think that it is a code-smell. It works for quick and dirty though. A more testable and better approach would be to pass an object that represents your domain (the need to see two these two values).
you can try this
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
To return 2 values I usually use Pair class from http://blog.o-x-t.com/2007/07/16/generic-pair-net-class/.
If you need to return from method 2 values that describe the range, e.g. From/To or Min/Max, you can use FromToRange class.
public class FromToRange<T>
{
public T From { get; set; }
public T To { get; set; }
public FromToRange()
{
}
public FromToRange(T from, T to)
{
this.From = from;
this.To = to;
}
public override string ToString()
{
string sRet = String.Format("From {0} to {1}", From, To);
return sRet;
}
public override bool Equals(object obj)
{
if (this == obj) return true;
FromToRange<T> pair = obj as FromToRange<T>;
if (pair == null) return false;
return Equals(From, pair.From) && Equals(To, pair.To);
}
public override int GetHashCode()
{
return (From != null ? From.GetHashCode() : 0) + 29 * (To != null ? To.GetHashCode() : 0);
}
}

Categories