c# private and overload functions [duplicate] - c#

This question already has answers here:
What's a "static method" in C#?
(9 answers)
Closed 8 years ago.
Why is MainWindow/this.ab hidden and cannot be seen? I suppose private should be seen inside mainWindows.
It seems like C# throws error Not all code return path value if I put return not at the end of the method.
Can c# return string and void at the same time? If I am wrong, what is the better code? In PHP,the code easily works. I need to know how it can get to work in C#.
public static string a(string type,string a)
{
return MainWindow.ab(type, a);
}
public static void a(string type)
{
MainWindow.ab(type);
}
private string ab(string type,string a=null)
{
if (type == "1")
{
return "1";
}
}

Better code is
public static string a(string type,string a)
{
return MainWindow.ab(type, a);
}
public static string a(string type)
{
return MainWindow.ab(type);
}
private static string ab(string type,string a=null)
{
if (type == "1")
return "1";
else
return null;
}
Why does MainWindow/this.ab is hidden and cannot be see ?
Because method is not correct and is not static.
Can c# return string and void same time ?
No, you can return null instead using of void

If you want to use 'ab' method as you use it in your example, ab should be defined as follows inside MainWindow:
public static string ab(...)
In regard of "return" error - not all execution paths return a string, e.g. if type != "1", return value is not provided.

Related

How to convert the integer associated with a value of an enum to string [duplicate]

I have the following enum:
public enum Urgency {
VeryHigh = 1,
High = 2,
Routine = 4
}
I can fetch an enum "value" as string like this:
((int)Urgency.Routine).ToString() // returns "4"
Note: This is different from:
Urgency.Routine.ToString() // returns "Routine"
(int)Urgency.Routine // returns 4
Is there a way I can create an extension class, or a static utliity class, that would provide some syntactical sugar? :)
You should just be able to use the overloads of Enums ToString method to give it a format string, this will print out the value of the enum as a string.
public static class Program
{
static void Main(string[] args)
{
var val = Urgency.High;
Console.WriteLine(val.ToString("D"));
}
}
public enum Urgency
{
VeryHigh = 1,
High = 2,
Low = 4
}
In order to achieve more "human readable" descriptions for enums (e.g. "Very High" rather than "VeryHigh" in your example) I have decorated enum values with attribute as follows:
public enum MeasurementType
{
Each,
[DisplayText("Lineal Metres")]
LinealMetre,
[DisplayText("Square Metres")]
SquareMetre,
[DisplayText("Cubic Metres")]
CubicMetre,
[DisplayText("Per 1000")]
Per1000,
Other
}
public class DisplayText : Attribute
{
public DisplayText(string Text)
{
this.text = Text;
}
private string text;
public string Text
{
get { return text; }
set { text = value; }
}
}
Then, used an extension method like this:
public static string ToDescription(this Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(
typeof(DisplayText),
false);
if (attrs != null && attrs.Length > 0)
return ((DisplayText)attrs[0]).Text;
}
return en.ToString();
}
You can then just call myEnum.ToDescription() in order to display your enum as more readable text.
If you want to just deal with this enum, use Mark Byer's solution.
For a more general solution:
public static string NumberString(this Enum enVal)
{
return Convert.ToDecimal(enVal).ToString("0");
}
Converting to decimal means you don't need to deal with the 8 different allowed underlying integral types explicitly, as all of them convert losslessly to decimal but not to each other (ulong and long don't convert losslessly between each other but both can handle all the rest). Doing that would probably be faster (esp. if you pick well in your order of comparison), but a lot more verbose for relatively little gain.
Edit:
The above isn't as good as Frankentosh's though, Frankentosh saw through the question to the real problem and solves it very eloquently.
Great stuff ... I have now added an extension method to my project
public static class EnumExtensions
{
public static string NumberString(this Enum enVal)
{
return enVal.ToString("D");
}
}
Now I can get the int value - as a string - by calling Urgency.Routine.NumberString(); Thanks to Frankentosh and Jon :)
a simple approach
((Urgency)4).ToString() // returns "Routine"
You can write an extension method for your specific type:
public static class UrgencyExtension
{
public static string ToIntegerString(this Urgency u)
{
return ((int)u).ToString();
}
}
Use as follows:
Urgency u = Urgency.Routine;
string s = u.ToIntegerString();
How about a little reflection? Should work with all underlying types.
public static class EnumTools
{
public static string ToRawValueString(this Enum e)
{
return e
.GetType()
.GetFields(BindingFlags.Public | BindingFlags.Static)
.First(f => f.Name==e.ToString())
.GetRawConstantValue()
.ToString();
}
}
Then:
Console.WriteLine(Urgency.High.ToRawValueString()); //Writes "2"
If you wanted, you could make the extension method work for all enums:
public static string ToValueString(this Enum enumValue)
{
if (enumValue.GetType().GetEnumUnderlyingType() == typeof(int))
return ((int)(object)enumValue).ToString();
else if (enumValue.GetType().GetEnumUnderlyingType() == typeof(byte))
return ((byte)(object)enumValue).ToString();
...
}

Universal DBNull check

I have a VB.Net function that is useful for checking if a database record is null or not, and replace it with a default value if it is.
Public Function NZ(input As Object, Optional ifNull As Object = "") As Object
If IsDBNull(input) Or input Is Nothing Then
Return ifNull
Else
Return input
End If
End Function
I'm trying to get the same functionality in C#, but it doesn't like using objects the same way.
The closest I've gotten is
public static object NZ(object input, object ifNull)
{
if(input == DBNull.Value || input == null)
{
return ifNull;
}
else
{
return input;
}
}
but I get several errors with "cannot convert object to string" and the like.
I have tried to make a more specific version
public static string NZ(string input, string ifNull)
{
if (input == DBNull.Value || input == null)
{
return ifNull;
}
else
{
return input;
}
}
but that gives a "Operator '==' cannot be applied to operands of type string and DBNull"
I'm hoping there is an easy way to do this.
Use Convert.IsDbNull
The code will be something like this:
public static string NZ(object input, string ifNull)
{
return Convert.IsDbNull(input) ? ifNull : input;
}
If you want it to be more concise, write an extension method:
public static class DbNullExt
{
public static string ValueOrDefault(this object input, string ifNull)
=> Convert.IsDbNull(input) ? ifNull : input?.ToString();
public static string ValueOrDefaultIfDbNullOrNull(this object input, string ifNull)
=> Convert.IsDbNull(input) ? ifNull : input?.ToString() ?? ifNull;
}
And then simply invoke it as
var valueOrDefault = input.ValueOrDefault("ifItIsDbNull");
Use Information.IsDBNull
public object NZ(object input, object ifNull)
{
if (Information.IsDBNull(input) || input == null)
return ifNull;
else
return input;
}

Enable static contract checker to prove a Property non-null based on some other property

Assume the following code:
public class CC3
{
private string _field;
private bool _someFlag;
public string Property
{
get { return _field; }
}
public bool SomeFlag
{
get { return _someFlag; }
}
public void SetField()
{
_field = " foo ";
_someFlag = true;
}
public string Method()
{
Contract.Requires(SomeFlag);
return Property.Trim();
}
}
The static checker of Code Contracts complains about the return statement of Method:
Possibly calling a method on a null reference 'this.Property'
What do I have to do to enable the static checker to prove that Property can never be null if SomeFlag is true?
You can give the static analysis a helping hand using Contract.Assume:
public string Method()
{
Contract.Requires(SomeFlag);
Contract.Assume(Property != null);
return Property.Trim();
}
Or actually add the check as a Contract.Requires in its own right. After all, just because you can manually prove it to be true for now, you can't guarantee that will always be the case when the code gets modified. In fact, consider whether SomeFlag being true is actually a requirement at all. Perhaps this is a cleaner solution:
public string Method()
{
Contract.Requires(Property != null);
return Property.Trim();
}
The only way to prove that it is not null is to prove that it is not null. Ideally you could use an invariant if you would convert to auto properties. For this example you could rewrite the property to ensure that null is not a possible result:
public string Property
{
get {
Contract.Ensures(Contract.Result<string>() != null);
return _field ?? String.Empty;
}
}

How can I access to the method in class that returns a Generic Type

I have a class named config with two string fields named key paramValue and parameterPath.
When I apply the ChooseType method of the class, the method has to return one variable paramValue in different types (Int or bool or String).
I implemented it as follow:
class ConfigValue
{
public string paramPath;
private string paramValue;
public enum RetType {RetInt, RetBool, RetString};
public T PolimorphProperty<T>(RetType how)
{
{
switch (how)
{
case RetType.RetInt:
return (dynamic)int.Parse(paramValue);
case RetType.RetBool:
return (dynamic)Boolean.Parse(paramValue);
case RetType.RetString:
return (T)(object)paramValue;
default:
throw new ArgumentException("RetType not supported", "how");
}
}
}
}
My question is how can i access to the PolimorphProperty method in ConfigValue class, to retrive for examlple paramValue Int type.
Having both T and RetType is redundant. It should be something like this:
class ConfigValue
{
public string paramPath;
private string paramValue;
public T PolimorphProperty<T>()
{
return (T)Convert.ChangeType(paramValue, typeof(T));
}
}
Call it like configValue.PolimorphProperty<int>().
Or if you need to implement the type conversion manually, you can do something like this:
class ConfigValue
{
public string paramPath;
private string paramValue;
public T PolimorphProperty<T>()
{
if (typeof(T) == typeof(MySpecialType))
return (T)(object)new MySpecialType(paramValue);
else
return (T)Convert.ChangeType(paramValue, typeof(T));
}
}
I think following code best matches what you want (i have tested it before writing here...)
public T PolimorphProperty<T>()
{
object tt = Convert.ChangeType(paramValue, typeof(T));
if (tt == null)
return default(T);
return (T) tt;
}
And you can call the code like this:
int ret = cv.PolimorphProperty<int>();
Notes:
You really do not need to pass anything in the param list to determine the type of the returned value.
Make sure you put try-catch wherever you are checking the appropraite type for your future usage.

String.IsNullOrBlank Extension Method

I continuously check string fields to check if they are null or blank.
if(myString == null || myString.Trim().Length == 0)
{
throw new ArgumentException("Blank strings cannot be handled.");
}
To save myself a bit of typing is it possible to create an extension method for the String class that would have the same effect? I understand how extension methods can be added for a class instance but what about adding a static extension method to a class?
if(String.IsNullOrBlank(myString))
{
throw new ArgumentException("Blank strings cannot be handled.");
}
You could do:
public static bool IsNullOrBlank(this String text)
{
return text==null || text.Trim().Length==0;
}
And then call it like this:
if(myString.IsNullOrBlank())
{
throw new ArgumentException("Blank strings cannot be handled.");
}
This works because C# allows you to call extension method on null instances.
I know this is an old question but since it was bumped and it hasn't been mentioned already, as of .NET 4.0 you can simply use the String.IsNullOrWhiteSpace method to achieve the same result.
You can safely use an extension method on the instance:
public static class StringExtensions
{
public static bool IsNullOrBlank(this string s)
{
return s == null || s.Trim().Length == 0;
}
}
Test cases:
string s = null;
Assert.IsTrue(s.IsNullOrBlank());
s = " ";
Assert.IsTrue(s.IsNullOrBlank());
It looks a bit weird though, and I would instead figure out why your strings need to be checked for this case so often. If you fix them at the source, you won't have to be so paranoid about them later!
Can you add static methods to existing classes? The answer is no, and the value would be pretty thin, because you'd still need to know which class name to type first; with extension methods, the advantage is that you start with a variable name and autocompletion shows you things that are applicable to it.
Another point often made is that extension methods should always throw an exception as soon as possible if their first argument is null. However, I think that rule is overkill if the method mentions in its name that it is designed to check for null.
The real problem you have is that you want to neatly and readably run some code after checking for a null reference. One way to capture that pattern is in my answer to this question.
An overload to the existing answers could be:
public static bool IsNullOrBlank(this String text, Action<String> doWhat)
{
if (text!=null && text.Trim().Length>0)
doWhat(text);
}
Would be helpful if you only want to run code given a valid value.
Not a super useful example, but just showing the usage:
Name.IsNullOrBlank(name=>Console.WriteLine(name));
A bit late. But you can also put the code to throw an exception in an extension method too. I have two methods (for ArgumentNullException and NullReferenceException).
// strings
public static bool NullBlankCheck(this string s, string message = "",
bool throwEx = true)
{
return Check<NullReferenceException>(s.IsNullOrBlank(), throwEx, message);
}
public static bool NullBlankCheckArgument(this string s, string message = "",
bool throwEx = true)
{
return Check<ArgumentException>(s.IsNullOrBlank(), throwEx, message);
}
private static bool Check<T>(bool isNull, bool throwEx, string exceptionMessage)
where T : Exception
{
if (throwEx && isNull)
throw Activator.CreateInstance(typeof(T), exceptionMessage) as Exception;
return isNull;
}
public static bool IsNullOrBlank(this string s)
{
return string.IsNullOrEmpty(s) || s.Trim().Length == 0;
}
nunit tests:
Assert.Throws<NullReferenceException>(() =>
{
"".NullEmptyCheck();
});
Assert.Throws<ArgumentException>(() =>
{
"".NullEmptyCheckArgument();
});
And then use it as:
public void Method(string someStr)
{
someStr.NullBlankCheckArgument();
// do something
var str = someMethod();
str.NullBlankCheck();
}
public static bool IsNullOrEmptyTrimmed(string value)
{
return (value == null || value.Length == 0) ?
true : value.Trim().Length == 0;
}
or
public static bool IsNullOrEmpty(this String value, bool checkTrimmed)
{
var b = String.IsNullOrEmpty(value);
return checkTrimmed ? (b && value.Trim().Length > 0) : b;
}
Although, this question was asked over a decade ago, I see no one has mentioned that there is a built in string method for handling this.
Therefore, please use string.IsNullOrWhitespace() instead. No hacking anything in, use the language feature and you're just fine.
With a few tricks, you make it look like you've added to the String class in any one cs file:
namespace JDanielSmith
{
public static class String
{
public static bool IsNullOrBlank(string text)
{
return text == null || text.Trim().Length == 0;
}
}
}
(note, this is not an extension method, see my comment).
Then, in some other CS file:
using String = JDanielSmith.String;
namespace Foo.Bar.Baz
{
class Program
{
static void test(string myString)
{
if (String.IsNullOrBlank(myString))
{
throw new ArgumentException("Blank strings cannot be handled.");
}
}
...
Notice the "desired" syntax of String.IsNullOrBlank(). I'm not necessarily suggesting that you actually do things this way, just pointing out how you could set things up to make your code work.
public static bool IsNull(this object o)
{
return string.IsNullOrEmpty(o.ToStr());
}
public static bool IsNotNull(this object o)
{
return !string.IsNullOrEmpty(o.ToStr());
}
public static string ToStr(this object o)
{
return o + "";
}

Categories