Forcing the use of a specific overload of a method in C# - c#-3.0

I have an overloaded generic method used to obtain the value of a property of an object of type PageData. The properties collection is implemented as a Dictionary<string, object>. The method is used to avoid the tedium of checking if the property is not null and has a value.
A common pattern is to bind a collection of PageData to a repeater. Then within the repeater each PageData is the Container.DataItem which is of type object.
I wrote the original extension method against PageData:
public static T GetPropertyValue<T>(this PageData page, string propertyName);
But when data binding, you have to cast the Container.DataItem to PageData:
<%# ((PageData)Container.DataItem).GetPropertyValue("SomeProperty") %>
I got a little itch and wondered if I couldn't overload the method to extend object, place this method in a separate namespace (so as not to pollute everything that inherits object) and only use this namespace in my aspx/ascx files where I know I've databound a collection of PageData. With this, I can then avoid the messy cast in my aspx/ascx e.g.
// The new overload
public static T GetPropertyValue<T>(this object page, string propertyName);
// and the new usage
<%# Container.DataItem.GetPropertyValue("SomeProperty") %>
Inside the object version of GetPropertyValue, I cast the page parameter to PageData
public static T GetPropertyValue<T>(this object page, string propertyName)
{
PageData data = page as PageData;
if (data != null)
{
return data.GetPropertyValue<T>(propertyName);
}
else
{
return default(T);
}
}
and then forward the call onto, what I would expect to be PageData version of GetPropertyValue, however, I'm getting a StackOverflowException as it's just re-calling the object version.
How can I get the compiler to realise that the PageData overload is a better match than the object overload?

The extension method syntax is just syntactic sugar to call static methods on objects. Just call it like you would any other regular static method (casting arguments if necessary).
i.e.,
public static T GetPropertyValue<T>(this object page, string propertyName)
{
PageData data = page as PageData;
if (data != null)
{
//will call the GetPropertyValue<T>(PageData,string) overload
return GetPropertyValue<T>(data, propertyName);
}
else
{
return default(T);
}
}
[edit]
In light of your comment, I wrote a test program to see this behavior. It looks like it does go with the most local method.
using System;
using Test.Nested;
namespace Test
{
namespace Nested
{
public static class Helper
{
public static void Method(this int num)
{
Console.WriteLine("Called method : Test.Nested.Helper.Method(int)");
}
}
}
static class Helper
{
public static void Method(this object obj)
{
Console.WriteLine("Called method : Test.Helper.Method(object)");
}
}
class Program
{
static void Main(string[] args)
{
int x = 0;
x.Method(); //calls the object overload
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.WriteLine();
}
}
}
To make sure the nesting is not affecting anything, tried this also removing the object overload:
using System;
using Test.Nested;
namespace Test
{
namespace Nested
{
public static class Helper
{
public static void Method(this int num)
{
Console.WriteLine("Called method : Test.Nested.Helper.Method(int)");
}
}
}
static class Helper
{
public static void Method(this string str)
{
Console.WriteLine("Called method : Test.Helper.Method(string)");
}
}
class Program
{
static void Main(string[] args)
{
int x = 0;
x.Method(); //calls the int overload
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.WriteLine();
}
}
}
Sure enough, the int overload is called.
So I think it's just that, when using the extension method syntax, the compiler looks within the current namespace first for appropriate methods (the "most local"), then other visible namespaces.

It should already be working fine. I've included a short but complete example below. I suggest you double-check your method signatures and calls, and if you're still having problems, try to come up with a similar short-but-complete program to edit into your question. I suspect you'll find the answer while coming up with the program, but at least if you don't, we should be able to reproduce it and fix it.
using System;
static class Extensions
{
public static void Foo<T>(this string x)
{
Console.WriteLine("Foo<{0}>(string)", typeof(T).Name);
}
public static void Foo<T>(this object x)
{
Console.WriteLine("Foo<{0}>(object)", typeof(T).Name);
string y = (string) x;
y.Foo<T>();
}
}
class Test
{
static void Main()
{
object s = "test";
s.Foo<int>();
}
}

Related

Reusable BooleanExpression in QueryDSL

I'm just getting started using QueryDSL with Spring Data JPA. I have a class where I'm storing all of my predicates, so that in my service methods, I can just call findAll() or findOne() on my repositories by passing in the boolean expression. Here's an example:
Predicate class method:
public static BooleanExpression byCode(String code) {
return QHeading.heading.code.eq(code);
}
Service class method:
public Iterable<Heading> getByCode(final String code) {
return headingRepository.findAll(byCode(code));
}
This works fine, but in the case where one heading is the child of another heading, I'd like to reuse the same method from my predicate class, just wrapping it in another method that returns the parent heading, rather than the child that matches the boolean expression. However, I'm having a bit of trouble figuring out the correct way to do this.
So, it would be something like this:
Predicate methods:
public static BooleanExpression byCode(String code) {
return QHeading.heading.code.eq(code);
}
public static BooleanExpression byChildCode(String code) {
QHeading.heading.childHeadings.eq(byCode(code));
}
Service method:
public Iterable<Heading> getByChildCode(final String code) {
return headingRepository.findAll(byChildCode(code));
}
Obviously, the eq() method doesn't work, but is there a way to accomplish this, or is there a different way I should be going about this entirely?
You can either do it like this
public static BooleanExpression byCode(String code) {
return QHeading.heading.code.eq(code);
}
public static BooleanExpression byChildCode(String code) {
return QHeading.heading.childHeadings.any().code.eq(code);
}
or if you want more code reusal:
private static BooleanExpression byCode(QHeading heading, String code) {
return heading.code.eq(code);
}
public static BooleanExpression byCode(String code) {
return byCode(QHeading.heading, code);
}
public static BooleanExpression byChildCode(String code) {
return byCode(QHeading.heading.childHeadings.any(), code);
}

EF 5 Model First Partial Class Custom Constructor How To?

EF has generated for me some partial classes, each with a constructor, but it says not to touch them (example below), now if I make my own secondary partial class and I want to have a constructor that automatically sets some of the fields how do I do so as it would conflict?
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Breakdown.Models
{
using System;
using System.Collections.Generic;
public partial class Call
{
public Call()
{
this.Logs = new HashSet<Log>();
}
...
}
}
Partial methods can help you here, in the T4 Templates define a body-less partial method and call that inside the constructor.
public <#=code.Escape(entity)#>()
{
...
OnInit();
}
partial void OnInit();
Then in your partial class define the partial method and place inside that what you want to do in the constructor. If you don't want to do anything then you don't need to define the partial method.
partial class Entity()
{
partial void OnInit()
{
//constructor stuff
...
}
}
http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx
This is not possible.
Partial classes are essentially parts of the same class.
No method can be defined twice or overridden (same rule apply for the constructor also)
But You can use below mentioned Workaround :
//From file SomeClass.cs - generated by the tool
public partial class SomeClass
{
// ...
}
// From file SomeClass.cs - created by me
public partial class SomeClass
{
// My new constructor - construct from SomeOtherType
// Call the default ctor so important initialization can be done
public SomeClass(SomeOtherType value) : this()
{
}
}
for more information check Partial Classes, Default Constructors
I hope this will help to you.
I wanted to do the same recently and ended up modifying the T4 template so I could implement my own parameterless constructor manually. To accomplish this you can remove the constructor from the generated classes and move the instantiation of collections etc to outside the constructor so this:
public Call()
{
this.Logs = new HashSet<Log>();
}
becomes this:
private ICollection<Log> logs = new HashSet<Log>();
public virtual ICollection<Log> Logs
{
get { return this.logs; }
set { this.logs = value; }
}
The drawback I suppose is that the generated classes are not as "clean". That is you can't just have auto-implemented properties for your complex/nav types.
In your model.tt file you can prevent the constructor generation by removing the below code, commenting it out or by just putting in a false into the conditional so it never gets executed:
if (propertiesWithDefaultValues.Any() || complexProperties.Any())
{
#>
public <#=code.Escape(complex)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=code.Escape(edmProperty)#> =
<#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}
foreach (var complexProperty in complexProperties)
{
#>
this.<#=code.Escape(complexProperty)#> = new
<#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
}
#>
}
Then below this you need to do some modification where properties are generated for your complex and navigation types. Add a private var with object instantiation and a property for accessing the private var for each of these eg:
if (complexProperties.Any())
{
foreach(var complexProperty in complexProperties)
{
//generate private var + any instantiation
//generate property for accessing var
}
}
Depending on the complexity of your model there may be other areas you need to modify. Hopefully this gets you started.
If I well understand the question, you need this constructor when creating a new entity, that is an entity that was not persisted before.
My case was to set a default value to all datetime, that is initalize them to "the begining of time" : 1900-01-01.
In this case I use an entity factory
public static T GetNewEntity<T> () {
T e;
try {
e = Activator.CreateInstance<T>();
} catch {
e = default(T);
}
SetDefaults(e);
return e;
}
Each time I need a new Entity I use
Entity e = GetNewEntity<Entity>();
with SetDefaults as :
public static void SetDefaults (object o) {
Type T = o.GetType();
foreach ( MemberInfo m in T.GetProperties() ) {
PropertyInfo P = T.GetProperty(m.Name);
switch ( Type.GetTypeCode(P.PropertyType) ) {
case TypeCode.String :
if ( P.GetValue(o, null) == null )
P.SetValue(o, String.Empty, null);
break;
case TypeCode.DateTime :
if ( (DateTime)P.GetValue(o, null) == DateTime.MinValue )
P.SetValue(o, EntityTools.dtDef, null);
break;
}
}
}
full code is here
It could be rewrittent to consider the entity type and so on...
Add a base class:
public class CallBase
{
protected CallBase()
{
Initialize();
}
protected abstract void Initialize();
}
Add the partial class implementation in another file
public partial class Call: CallBase
{
protected override void Initialize();
{
...
}
}
The drawback is that the Initialization method will be called before the all collection creature.

Can you use a class inside of a function in C#

I was wondering if I could use a class inside of a function. I would the call the function in another file using using filename.FuntionName(); I made the class public so that it would more likely cooperate. Also, would using filename.FunctionName(); call the function from the other file, or just use it as a resource? Well, here is the code:
namespace file
{
public void file()
{
public class file
{
/*function
code*/
}
}
}
You cant declare classes inside functions like Java , however you can use var to create an anonymous type that are not visible outside the function
void file()
{
var file=new {
path="path",
size=200};
Console.WriteLine(file.path+" "+file.size);
}
I suspect what you're looking for is a static method.
namespace SomeNamespace
{
public class SomeClass
{
public static void CallMe()
{
Console.WriteLine("Hello World!");
}
}
}
Then you can call SomeNameSpace.SomeClass.CallMe() from elsewhere without having to create a new instance of SomeClass.
The correct way to declare a function:
namespace Company.Utilities.File
{
public class File
{
public File(string filename)
{
Filename = filename;
}
public string Filename { get; private set; }
public void Process()
{
// Some code to process the file.
}
public static void ProcessFile(string filename)
{
File file = new File(filename);
file.Process();
}
}
}
The point with the long namespace name is that it should be unique even when using assemblies from other companies (Third Part assemblies)
If you want to call the class like it was a function you should create a static function (like ProcessFile) then you can call File.ProcessFile(filename);

Calling Partial Methods in C#

i was recently digging on new partial methods in c#3.0, i understood the use of partial class, that it could be chunked into multiple file one contain the definition and other declaration, but i wanted to know,i created a partial class like below:
in class1.cs
partial class A
{
partial void Method();
}
in class2.cs
partial class A
{
partial void Method()
{
Console.WriteLine("Hello World");
}
}
now in class3.cs
class MainClass
{
static void Main()
{
A obj = new A();
obj.Method(); //Here i cannot call the "Method" method.
}
}
then whats the use of creating partial method, i read on MSDN that, at runtime, compiler compiles the class into one, in that case compiler should be getting the "Method" method implementation also, then why it dont allow me to call the "Method" method in the main method, can anyone correct me if i am wrong, and tell me why i am unable to call this partial method in main.
From MSDN
No access modifiers or attributes are allowed. Partial methods are
implicitly private.
It's a private method, so you can't call it from main.
You can call a partial method inside the constructor where the method is defined.
For example
public partial class classA
{
partial void mymethod();
}
public partial class classA
{
partial void mymethod()
{
Console.WriteLine("Invoking partial method");
}
public ClassA()
{
mymethod();
}
}
public class MainClass
{
static void Main()
{
ClassA ca=new ClassA();
}
}
That's it..now execute your code and see the result..
OutPut
Invoking partial method
Yes, we can't call it from Main(). Problem is not Partial method problem is method without specifier in a class is Private and private method can be called inside the class only.
Try creating a new public method in Partial class:
partial class A
{
partial void Method();
}
partial class A
{
partial void Method()
{
Console.WriteLine("Hello World");
}
public void Study()
{
Console.WriteLine("I am studying");
Method();
}
}
class MainClass
{
static void Main()
{
A obj = new A();
obj.Study();
}
}

Cast a CustomList<CustomClass> to IList<Interface>

(This is .Net 3.5) I have a class FooList which implements IList and a class FooClass which implements IFoo. A user requires IList<IFoo>. In my implementation, I create a FooList<FooClass>, called X. How do I code my return so that my FooList<FooClass> X becomes his IList<IFoo>?
If I try
return X.Cast( ).ToList( );
he gets an IList<IFoo>, but it is not my FooList; it is a List, and a new one at that.
This isn't going to work out, because a FooList<FooClass> is not an IList<IFoo>. This is why:
var myList = new FooList<FooClass>();
IFoo obj = new SomeOtherFooClass();
IList<IFoo> result = (IList<IFoo>)myList; // hypothetical, wouldn't actually work
result.Add(obj); // uh-oh, now myList has SomeOtherFooClass
You need to either make a copy or use an interface that is actually covariant on the contained type, like IEnumerable<T> instead of IList<T>. Or, if appropriate, you should declare your FooList<FooClass> as an FooList<IFoo> from the get-go instead.
Here is a small implementation that demonstrates my second suggestion:
public interface IFoo { }
public class FooClass : IFoo { }
public class FooList<T> : IList<T>
{
public void RemoveAt(int index) { /* ... */ }
/* further boring implementation of IList<T> goes here */
}
public static void ListConsumer(IList<IFoo> foos)
{
foos.RemoveAt(0); // or whatever
}
public static IList<IFoo> ListProducer()
{
// FooList<FooClass> foos = new FooList<FooClass>(); // would not work
FooList<IFoo> foos = new FooList<IFoo>();
foos.Add(new FooClass());
return foos; // a FooList<IFoo> is an IList<IFoo> so this is cool
}
public static void Demo()
{
ListConsumer(ListProducer()); // no problemo
}