Why is this extension method not working? - c#

public static string ToTrimmedString(this DataRow row, string columnName)
{
return row[columnName].ToString().Trim();
}
Compiles fine but it doesn't show up in intellisense of the DataRow...

My guess is you haven't included the namespace.

Ensure this method is in a static class of its own, separate class from the consuming DataRow.
namespace MyProject.Extensions
{
public static class DataRowExtensions
{
//your extension methods
}
}
In your consumer, ensure you're:
using MyProject.Extensions

I had this same issue. My mistake wasn't that I missed the static class or static method but that the class my extensions were on was not public.

In addition to a missing using, following case with the same symptom may occur:
If you are inside a method of the class itself (or one if its implementors / inheritors), you need to make use of this.
File extension.cs:
namespace a
{
public static void AExt(this A a) {}
}
File user.cs
namespace a
{
class A {}
class B : A
{
this.AExt();
// AExt() will not work without this.
}
}

If you are using different namespaces try this code.
namespace Extensions
{
public static class StringExtensions
{
public static bool IsNumeric(this string inputString)
{
return decimal.TryParse(inputString, out decimal result);
}
}
}
namespace Business
{
// add here other namespaces
using Extensions;
public static class Tools
{
public static bool Check(string inputString)
{
return inputString.IsNumeric();
}
}
}

I had this same issue. My mistake is the argument type is not same: defined one is Session, revokded one is ISession.

Related

Define assembly for extension method

I'm trying to use extension method, but the method is defined twice with same name.
Let's say A.Extensions.Ext() and B.Extensions.Ext() I need both references in my class and when trying
using A.Extensions;
using B.Extensions;
class C
{
public void Main()
{
somevalue.Ext();
}
}
I want to somehow define which method to use and I don't know how to do that.
Thanks for help!
There is a way to choose an extension method to be used
Assume you have two classes with extension methods for string
public static class Extension1
{
public static string GetLowerCaseResult(this string str)
{
return str.ToLowerInvariant();
}
}
public static class Extension2
{
public static string GetLowerCaseResult(this string str)
{
return str.ToLowerInvariant();
}
}
to call it in Main method you have to explicitly specify class and method in this way
static void Main(string[] args)
{
var str = "QWERTY";
Extension2.GetLowerCaseResult(str);
Console.Read();
}

I am trying to execute the following code in C# but its somehow giving me an error

namespace A
{
public enum ABC
{
}
public class ClassA
{
static ClassA()
{}
public static bool f_name
{
}
//All the rest of the functions are also static
}
}
namespace B
{
using A;
public partial class ClassB
{
private bool x;
public ClassB()
{}
static void Main()
{
x = ClassA.f_name;
}
}
}
both the namespaces are in different files. On running this code, ClassA.f_name doesn't work. It's ignored somehow. When I put a watch on it, it says this "The name 'ClassA' does not exist in the current context". Can anyone tell me why ? also what do I need to do to fix this ?
When I used "A.ClassA.f_name", then it worked fine. But I shouldn't need to write "A." since I included namespace A already. Thanks in advance for the help.
I'm running this in Visual Studio 2010, Windows 7. I have put the build order such that namespace A is compiled before namespace B.
the problem you have is due to the fact that you need to access the static class A with a non static variable x. chnage your classes to:
namespace A
{
public enum ABC
{
}
public class ClassA
{
static ClassA()
{ }
public static bool f_name
{
get { return true; }
}
//All the rest of the functions are also static
}
}
namespace B
{
using A;
public partial class ClassB
{
/// changed this to static to match access on class A
private static bool x;
public ClassB()
{ }
static void Main()
{
x = ClassA.f_name;
}
}
}
and all will be fine
you are using two different namespaces .hence it got resolved when you added reference to namespace A.

How Can I inherit the string class?

I want to inherit to extend the C# string class to add methods like WordCount() and several many others but I keep getting this error:
Error 1 'WindowsFormsApplication2.myString': cannot derive from sealed
type 'string'
Is there any other way I can get past this ? I tried with string and String but it didn't work.
Another option could be to use an implicit operator.
Example:
class Foo {
readonly string _value;
public Foo(string value) {
this._value = value;
}
public static implicit operator string(Foo d) {
return d._value;
}
public static implicit operator Foo(string d) {
return new Foo(d);
}
}
The Foo class acts like a string.
class Example {
public void Test() {
Foo test = "test";
Do(test);
}
public void Do(string something) { }
}
System.String is sealed, so, no, you can't do that.
You can create extension methods. For instance,
public static class MyStringExtensions
{
public static int WordCount(this string inputString) { ... }
}
use:
string someString = "Two Words";
int numberOfWords = someString.WordCount();
If your intention behind inheriting from the string class is to simply create an alias to the string class, so your code is more self describing, then you can't inherit from string. Instead, use something like this:
using DictKey = System.String;
using DictValue= System.String;
using MetaData = System.String;
using SecurityString = System.String;
This means that your code is now more self describing, and the intention is clearer, e.g.:
Tuple<DictKey, DictValue, MetaData, SecurityString> moreDescriptive;
In my opinion, this code shows more intention compared to the same code, without aliases:
Tuple<string, string, string, string> lessDescriptive;
This method of aliasing for more self describing code is also applicable to dictionaries, hash sets, etc.
Of course, if your intention is to add functionality to the string class, then your best bet is to use extension methods.
You cannot derive from string, but you can add extensions like:
public static class StringExtensions
{
public static int WordCount(this string str)
{
}
}
What's wrong with a helper class? As your error message tells you, String is sealed, so your current approach will not work. Extension methods are your friend:
myString.WordCount();
static class StringEx
{
public static int WordCount(this string s)
{
//implementation.
}
}
You can't inherit a sealed class (that's the whole point of it) and the reason why it wouldn't work with both string and System.String is that the keyword string is simply an alias for System.String.
If you don't need to access the internals of the string class, what you can do is create an Extension Method, in your case :
//note that extension methods can only be declared in a static class
static public class StringExtension {
static public int WordCount(this string other){
//count the word here
return YOUR_WORD_COUNT;
}
}
You still won't have access to the private methods and properties of the string class but IMO it's better than writing :
StringHelper.WordCount(yourString);
That's also how LINQ works.
The string class is marked sealed because you are not supposed to inherit from it.
What you can do is implement those functions elsewhere. Either as plain static methods on some other class, or as extension methods, allowing them to look like string members.

Is there any other way to implement Overriding (not virtual and override) in C# / .NET?

Could anyone tell me is there any other way a method can be overridden without using virtual/abstract/override in C#/.NET, Please provide me with an example.Please provide with an example...
(what i am thinking is Extension methods am i correct.....)
No, there is no other way. You can hide an existing method with new if the base method is not marked as virtual, however it does not have the same effect (there is no polymorphism - the call will be dispatched based on the variable type, not on the actual object type).
Extension will not work in this case. Objects own properties and methods take precedence. However you can overload a method using extensions.
You can override methods defined in the extensions, by keeping your extensions closer in the namespace to the place where you are going to use it.
Example:
namespace ConsoleApplication2
{
using System;
using ConsoleApplication3;
internal class Program
{
private static void Main(string[] args)
{
ThirdPartyClass t = new ThirdPartyClass();
Console.WriteLine(t.Fun("hh"));
Console.WriteLine(t.Fun(1));
}
}
public static class LocalExtension
{
public static string Fun(this ThirdPartyClass test, int val)
{
return "Local" + val;
}
public static string Fun(this ThirdPartyClass test, string val)
{
return "Local" + val;
}
}
}
namespace ConsoleApplication3
{
public class ThirdPartyClass
{
public virtual string Fun(string val)
{
return "ThirdParty" + val.ToUpper();
}
}
public static class ThripartyExtension
{
public static string Fun(this ThirdPartyClass test, int val)
{
return "ThirdParty" + val;
}
}
}
You can use the "new" keyword on your method to "hide" a method that was not declared as abstract/virtual, however if the method is called from a variable type-casted as the base class, it won't call your new method. This is the similar to overriding.
Example:
public class A
{
public string GetName() { return "A"; }
}
public class B : A
{
// this method overrides the original
public new string GetName() { return "B"; }
}
Extension methods allow you to add new methods to any class even if you don't have their source code or they're sealed. This is not the same as overriding
public sealed class A // this could even be from a dll that you don't have source code to
{
}
public static class AExtensionMethods
{
// when AdditionalMethod gets called, it's as if it's from inside the class, and it
// has a reference to the object it was called from. However, you can't access
// private/protected fields.
public static string AdditionalMethod(this A instance)
{
return "asdf";
}
}
Another option is to use interfaces so that you can have two completely different objects that both have the same method, but when called from a variable type-casted as the interface, it looks similar to overriding.
You could also use a form of Proxy Mocking framework like Microsoft Moles, or CastleWindsor -> They have a way of instantiating a "proxy" object that has the same interface as the real object, but can provide a different implementation for each method.

How do you write a C# Extension Method for a Generically Typed Class

This should hopefully be a simple one.
I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class.
How should this extension method look?
My first intuitive thought is something like this:
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle(this ViewPage<Type> v)
{
return "";
}
}
}
Solution
The general solution is this answer.
The specific solution to extending the System.Web.Mvc.ViewPage class is my answer below, which started from the general solution.
The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type.
I don't have VS installed on my current machine, but I think the syntax would be:
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle<T>(this ViewPage<T> v)
{
return "";
}
}
}
Thanks leddt.
Doing that yielded the error:
The type 'TModel' must be a reference
type in order to use it as parameter
'TModel' in the generic type or method
which pointed me to this page, which yielded this solution:
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle<T>(this ViewPage<T> v)
where T : class
{
return "";
}
}
}
It just needs the generic type specifier on the function:
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle<Type>(this ViewPage<Type> v)
{
return "";
}
}
}
Edit: Just missed it by seconds!
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle<T>(this ViewPage<T> view)
where T : class
{
return "";
}
}
}
You may also need/wish to add the "new()" qualifier to the generic type (i.e. "where T : class, new()" to enforce that T is both a reference type (class) and has a parameterless constructor.
Glenn Block has a good example of implementing a ForEach extension method to IEnumerable<T>.
From his blog post:
public static class IEnumerableUtils
{
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
foreach(T item in collection)
action(item);
}
}
If you want the extension to only be available for the specified type
you simply just need to specify the actual type you will be handling
something like...
public static string GetDefaultPageTitle(this ViewPage<YourSpecificType> v)
{
...
}
Note intellisense will then only display the extension method when you declare your (in this case) ViewPage with the matching type.
Also, best not to use the System.Web.Mvc namespace, I know its convenient to not have to include your namespace in the usings section, but its far more maintainable if you create your own extensions namespace for your extension functions.
Here's an example for Razor views:
public static class WebViewPageExtensions
{
public static string GetFormActionUrl(this WebViewPage view)
{
return string.Format("/{0}/{1}/{2}", view.GetController(), view.GetAction(), view.GetId());
}
public static string GetController(this WebViewPage view)
{
return Get(view, "controller");
}
public static string GetAction(this WebViewPage view)
{
return Get(view, "action");
}
public static string GetId(this WebViewPage view)
{
return Get(view, "id");
}
private static string Get(WebViewPage view, string key)
{
return view.ViewContext.Controller.ValueProvider.GetValue(key).RawValue.ToString();
}
}
You really don't need to use the Generic version as the generic one extends the non-generic one so just put it in the non-generic base class and you're done :)

Categories

Resources