Extending string with Extension Methods (C# 3.0)? - c#

I know I can extend the string class like so:
public static class EMClass
{
public static int ToInt32Ext(this string s)
{
return Int32.Parse(s);
}
public static int ToInt32Static(string s)
{
return Int32.Parse(s);
}
}
And use it like this:
string x = "12";
x.ToInt32Ext()
But how can I make it to where I can use it like this:
int x = string.ToInt32("15");

I don't think you can do "static" extension methods.

Dude, do you have any problems with Int32.Parse() ?

What I did in our project at work is created a class called Strings which is where I put all of our extension methods. That way you have something that visually looks similar to string.
You can call the extension method in your example like so too (not all people might like this, but I use this myself depending on the code I'm working on):
int x = "15".ToInt32();

Extension methods only apply to instances of a class, not the class itself. You can't extend a class with a class method using an extension. Note that you should easily be able to do what you want with an extension method, just using.
var fifteen = "15".ToInt32Ext();

You can't really do this... the closest you are going to get is this:
public static class Ext
{
public static class String
{
public static int ToInt32(string val)
{
return Int32.Parse(val);
}
}
}
//Then call:
Ext.String.ToInt32("32");
Which i'm surprised the compiler even allows you to name a class "String"
Just for entertainment, i thought of another fun way to do it, though i would never recommend this. Add:
using String = NameSpace1.Ext.String;
//Then you can access it as:
String.ToInt32("32"); //Yipes

Personally, I don't see a lot of use for an extension-method wrapper to a method call that's already a short one-liner. On the other hand, wrapping the Int32.TryParse pattern to return a nullable int can be pretty convenient:
public static int? ToInt32(this string input)
{
if (String.IsNullOrEmpty(input))
return null;
int parsed;
if (Int32.TryParse(input, out parsed))
return parsed;
return null;
}
This allows you to parse a value that might not be present, or might not contain an integer, and provide a default value in a single line of code:
int id = Request.QueryString["id"].ToInt32() ?? 0;

Related

how to write the methods inside the enum in c# [duplicate]

In Java, it's possible to have methods inside an enum.
Is there such possibility in C# or is it just a string collection and that's it?
I tried to override ToString() but it does not compile. Does someone have a simple code sample?
You can write extension methods for enum types:
enum Stuff
{
Thing1,
Thing2
}
static class StuffMethods
{
public static String GetString(this Stuff s1)
{
switch (s1)
{
case Stuff.Thing1:
return "Yeah!";
case Stuff.Thing2:
return "Okay!";
default:
return "What?!";
}
}
}
class Program
{
static void Main(string[] args)
{
Stuff thing = Stuff.Thing1;
String str = thing.GetString();
}
}
You can write an extension method for your enum:
How to: Create a New Method for an Enumeration (C# Programming Guide)
Another option is to use the Enumeration Class created by Jimmy Bogard.
Basically, you must create a class that inherits from his Enumeration. Example:
public class EmployeeType : Enumeration
{
public static readonly EmployeeType Manager
= new EmployeeType(0, "Manager");
public static readonly EmployeeType Servant
= new EmployeeType(1, "Servant");
public static readonly EmployeeType Assistant
= new EmployeeType(2, "Assistant to the Regional Manager");
private EmployeeType() { }
private EmployeeType(int value, string displayName) : base(value, displayName) { }
// Your method...
public override string ToString()
{
return $"{value} - {displayName}!";
}
}
Then you can use it like an enum, with the possibility to put methods inside it (among another things):
EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager
You can download it with NuGet.
Although this implementation is not native in the language, the syntax (construction and usage) is pretty close to languages that implement enums natively better than C# (Kotlin for example).
Nope. You can create a class, then add a bunch of properties to the class to somewhat emulate an enum, but thats not really the same thing.
class MyClass
{
public string MyString1 { get{ return "one";} }
public string MyString2 { get{ return "two";} }
public string MyString3 { get{ return "three";} }
public void MyMethod()
{
// do something.
}
}
A better pattern would be to put your methods in a class separate from your emum.
Since I came across, and needed the exact opposite of enum to string, here is a Generic solution:
static class EnumExtensions {
public static T GetEnum<T>(this string itemName) {
return (T) Enum.Parse(typeof(T), itemName, true);
}
}
This also ignores case and is very handy for parsing REST-Response to your enum to obtain more type safety.
Hopefully it helps someone
C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.
Use of classes is highly discouraged by Microsoft in this case, use (data)struct(ures) instead; The STRUCT is intended as a light class for data and its handlers and can handle functions just fine. C# and its compiler don't have the tracking and efficiency capabilities as one knows from JAVA, where the more times a certain class / method is used the faster it runs and its use becomes 'anticipated'. C# simply doesn't have that, so to differentiate, use STRUCT instead of CLASS.

C# type of enclosing class

Is there some way to specify the type of the enclosing class declaration statically? If i had an instance, I could clearly use typeof(this), but statically I don't see a way.
Something like (where this_type is a placeholder):
public class Message
{
public static readonly int SizeInBytes = Marshal.SizeOf(typeof(this_type));
}
Clearly, I could just use the actual type name, but I've got several classes that follow this pattern and would like something less copy/paste error prone.
You can use MethodBase.GetCurrentMethod().DeclaringType but typeof(Message) is probably the cleaner way
public class Message
{
public static readonly int SizeInBytes = Marshal.SizeOf(MethodBase.GetCurrentMethod().DeclaringType);
}
Btw, you'll get a runtime exception when you execute this code as it is trying to get the size of a managed object.
typeof(Message) would be the closest you'd get here, but I think you'd need to use a struct rather than a class to do this from what I recall.
Perhaps:
public class Message
{
public static readonly int SizeInBytes = Marshal.SizeOf(typeof(Message));
}
This way, 'Message' can also be static.
What about an extension method on the type and get it dynamically instead of pushing it to a readonly static variable?
public static class Extensions
{
public static int SizeOfType(this System.Type tp) {
return Marshal.SizeOf(tp);
}
public static int SizeOfObjectType(this object obj) {
return obj.GetType().SizeOfType();
}
}
// calling it from a method, 2 ways
var size1 = this.GetType().SizeOfType();
var size2 = this.SizeOfObjectType();
var size3 = typeof(string).SizeOfType();
var size4 = "what is my type size".SizeOfObjectType();
After a short google search, I've seen other people using reflection to accomplish what you are talking about, but that comes with the caveat that it is probably a lot more expensive than just typing out typeof(this_type). I'd sooner recommend just typing it out.
Type t = MethodBase.GetCurrentMethod().DeclaringType
.NET: Determine the type of “this” class in its static method

String as a variable (Dot-notation instead bracket-notation)?

In javascript, properties of objects can be accessed using dot-notation instead of bracket-notation -- object.propertyName can be used in place of object["propertyName"].
How can I do this in C#?
As an example, say I have a helper class to return values from a resource file:
public static class ResourceHelper
{
public static string get(string resourceName)
{
uint language = SPContext.Current.Web != null ? SPContext.Current.Web.Language : 1033;
return SPUtility.GetLocalizedString("$Resources:" + resourceName, "Comp.Dept.Proj.Farm\\Resources", language);
}
}
So here, instead of
ResourceHelper.get("SQL_CONNECTION_STRING")
would it be possible to do something like
ResourceHelper.SQL_CONNECTION_STRING
instead?
If yes, how? I feel this will make the code easier to read, IMO.
You may create a Property like this
public static string SqlConnectionString {
get {
return get("SQL_CONNECTION_STRING");
}
}
in your class but i guess you're looking for something doing that automagically...
You'll need to create a property for that.
In ResourceHelper.cs, add
public string SQL_CONNECTION_STRING
get{return get("SQL_CONNECTION_STRING"); }

How can I avoid ref parameters?

I have a method that has 2 ref parameters:
public void ReplaceSomething(ref int code, ref string name)
{
...
}
I want to avoid this, as it is not a good design (and scales poorly). What are my options?
I've though about using an anonymous object, but that doesn't seem like a good idea, either.
Object something = new { code = 1, name = "test" };
ReplaceSomething(something);
Are the code and the name closely linked together? If so, consider creating a type to put the two of them together. Then you can return a value of that type.
Alternatively, you might consider returning a Tuple<int, string>.
(In both cases you can accept an input parameter of the same type, of course. As you haven't shown any of your code, it's not really clear whether you use the existing values of the parameters, or whether they could basically be out parameters.)
Why don't you want to use ref arguments? That seems like a perfectly good way to change some caller values.
The other approach would be to implement a return value. Maybe you need to better explain what the problem is?
If these values are tightly coupled and "belong together" you could define a custom class that holds your properties and either return a new instance (assuming its immutable) of that or update its properties:
class Code
{
public int Value {get;set;}
public string Name {get;set;}
}
public Code UpdateCode(Code code)
{
...
}
If you need to return these values, you can either use a tuple
public Tuple<int, string> ReplaceSomething(int code, string name)
{
...
}
Or create your own class-wrapper that holds the values as properties
public Foo ReplaceSomething(int code, string name)
{
var foo = new Foo(){...};
return foo;
}
class Foo
{
public int IntValue{get;set;}
public string StringValue{get;set;}
}
Why would you change it? ref parameters make sense at times, and if this is one of those times - use them. You could introduce a new class that contains that pair of values, which only makes sense if those values come together often.
I say, keep it.
Based on your question, I could be way off. What do you mean by replacing ref? Are you looking to overload?
public void ReplaceSomething(int code, string name)
{
// ...
}
public void ReplaceSomething()
{
return ReplaceSomething(1, "test");
}
Edit:
ok, so you need to return the code and the name what are the calculations that need to be made? Jon Skeet's answer about a tuple could be right, or you might need a POCO that contains the code the name and the replaced
public void ReplaceSomething(int code, string name)
{
var replaced = new Replaced();
replaced.code = code;
replaced.name = name;
var r;
// do some replacement calculations
replaced.replaced = r;
return replaced;
}
public class Replaced {
public string name {get; set;}
public int code {get; set;}
public string replaced {get; set;}
}

Where do I put my extension method?

A senior member here gave me this code:
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + " ..";
}
He said to use it as an extension method. But where do I put this method? It looks like it adds something to .Net
Consider a class named StringExtensions like so:
static class StringExtensions
{
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ?
value :
value.Substring(0, maxChars) + " ..";
}
}
Be sure that whatever namespace you put this class in, you include a using declaration for that namespace.
Thus, for a full example:
StringExtensions.cs:
namespace My.Extensions
{
static class StringExtensions
{
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ?
value :
value.Substring(0, maxChars) + " ..";
}
}
}
Program.cs:
using System;
using My.Extensions;
namespace My.Program
{
static class Program
{
static void Main(string[] args)
{
string s = "Hello, World";
string t = s.Truncate(5);
Console.WriteLine(s);
Console.WriteLine(t);
}
}
}
By the way, you are not adding it to .NET. You are not even adding a new method to the class String. Rather, it's a compiler trick that makes static methods living in static classes with their first parameter declared as this *TypeName* *valueParameter* where *TypeName* is the name of a type, and *valueParameter* is the name of the parameter can be made to appear as an instance method on instances of the type with type name *TypeName*. That is
string t = s.Truncate(5);
is translated by the compiler into
string t = StringExtensions.Truncate(s, 5);
Put it in a static class, and use using on its namespace.
e.g.
namespace Foo
{
static class Extensions
{
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ?
value : value.Substring(0, maxChars) + " ..";
}
}
}
And then in a different file:
using Foo; //Don't forget this!
class Tester
{
static void Test()
{
Console.WriteLine("123456".Truncate(3));
}
}
Yes, use a static class. I organize in a separate project that I can use across solutions. I also organize in separate files grouped by what I'm extending such as strings, enums, io, datetime, etc
In addition to other answers: yes, it's a kind of extending .NET. More strictly speaking, extending already compiled classes. You can "add" methods to the classes which are not accessible for your modification. From the internal point of view, it's just a syntactic sugar: your methods cannot be seen by reflection. But for the users of your extension, it looks as if the methods were really added to the target class (well, with some distinctions).
The possibility to influence in some way the code that is already written is an essential part of object-oriented approach. In almost any OO language you can derive from some existing class and add some functionality to it this way (although this is not the preferred way for code reusing). In Objective C, you can modify existing classes using categories at compile time. In JavaScript, you can modify them even at runtime, using prototype.
As C# is not such a dynamic language as JavaScript is, modifying the existing classes is available in a somewhat limited form of extension methods.

Categories

Resources