I'm using Type.GetConstructor(Type.EmptyTypes) to get the default constructor for a class. It works if the class has a default constructor with no parameters (class A). But it doesn't work if a class has a constructor with all parameters optional (class B). Program doesn't know what the optional parameters are because it only needs the default constructor. What can statements can I use to make it work for both cases? Thanks, appreciate any help!
public class A
{
public A() {}
}
public class B
{
public B(int i = 0, string str = "") {}
}
Say I have the following class:
public class SomeClass
{
public SomeClass()
{
}
public SomeClass(int x)
{
}
public SomeClass(int x = 0, int y = 0)
{
}
}
Basically, you're asking for a query that will find the constructors that match constructor 1 and 3 above? If so, use this:
var constuctors = typeof(SomeClass).GetConstructors()
.Where(x => x.GetParameters().Count() == 0
|| x.GetParameters().Count(param => param.GetCustomAttributes(typeof(OptionalAttribute), false).Count() > 0) == x.GetParameters().Count());
Incredibly nasty query, but it gets the job done returning only 1 and 3 above.
The problem is that the C# compiler produces this:
public class B
{
// Methods
public B([Optional, DefaultParameterValue(0)] int i, [Optional, DefaultParameterValue("")] string str)
{
}
}
Something like below should work:
public static class TypeHelper {
public static ConstructorInfo GetDefaultConstructor<TType>() {
var type = typeof(TType);
return type.GetDefaultConstructor();
}
public static ConstructorInfo GetDefaultConstructor(this Type type) {
if(type == null) throw new ArgumentNullException("type");
var constructor = type.GetConstructor(Type.EmptyTypes);
if(constructor == null) {
var ctors =
from ctor in type.GetConstructors()
let prms = ctor.GetParameters()
where prms.All(p=>p.IsOptional)
orderby prms.Length
select ctor;
constructor = ctors.FirstOrDefault();
}
return constructor;
}
}
The problem is that optional parameters are nothing more than a compile time concept. You'll need to specify the constructor completely.
var ci = typeof(B).GetConstructor(new [] { typeof(int), typeof(string) });
You can write a help function that will invoke the constructor with the default values though. My example is not as robust as it should be but it should get you started.
static Func<T> CreateDefaultConstructor<T>(ConstructorInfo ci)
{
var l = new List<object>();
foreach (var p in ci.GetParameters())
{
if (p.IsOptional)
{
l.Add(p.RawDefaultValue);
}
}
return () => (T)ci.Invoke(l.ToArray());
}
The problem is that, in the case of B, it does not have a constructor with no parameters.
Optional arguments are a compile time construct - in the IL, it's a constructor with 2 parameters (which are flagged with attributes). As such, there is no default constructor as far as Reflection is concerned.
To get the one that has more optional parameters or an empty constructor at all, use:
typeof(myClass)
.GetConstructors()
.OrderBy(x => x.GetParameters().Length - x.GetParameters().Count(p => p.IsOptional))
.FirstOrDefault();
When a constructor, or any other method, has optional arguments it doesn't cause the compiler to generate multiple versions of the method. Instead it generates a single method which has all of the specified parameters. The default values are encoded in attributes attached to the method signature. These are used at the call site to make their values optional.
So here there is no default constructor but instead a single one with 2 parameters
Related
I have a simple question about constructors in C#. Will these two code snippets behave the same way?
Code snippet #1:
public class foo
{
public foo(string a = null, string b = null)
{
// do testing on parameters
}
}
Code snippet #2:
public class foo
{
public foo()
{
}
public foo(string a)
{
}
public foo(string a, string b)
{
}
}
EDIT:
And if I add this to the code snippet #1? It may look a really bad idea, but I'm working on refactoring a legacy code, so I'm afraid if I do sth that will cause damage to other piece of that uses that class.
public class foo
{
public foo(string a = null, string b = null)
{
if (a == null && b == null)
{
// do sth
}else if (a != null && b == null)
{
// do sth
}
if (a != null && b != null)
{
// do sth
}
else
{
}
}
}
The answer is no, the two are not going to behave the same.
The first snippet does not let your constructor decide if it has been called with a default parameter for a and/or b, or the caller has intentionally passed null. In other words, passing nulls intentionally becomes allowed, because you cannot implement a meaningful null check.
Another aspect in which these two code snippets would definitely differ - using constructors through a reflection:
The first snippet would provide one constructor. Reflection callers would need to deal with passing two parameters to it, or allowing optional parameters with binding flags (look at the demo provided by Jcl).
The second snippet would provide three separate constructors. Reflection callers would need to pick the one they wish to use.
No. Try using named arguments. The overload version will not compile. Because a hasn't been given a value in the latter case.
var test = new foo1(b: "nope");
var test2 = new foo2(b: "nope");//CS7036 : There is no argument given that corresponds to the required formal parameter of
if your are looking for a way to create an object with optional parameters just create inside your class a static factory method with optional or named parameter:
public class Foo
{
public Foo(string a, string b, string c) { }
public static Foo createInstance(string a = null, string b = null, string c = null) => new Foo(a, b, c);
}
I have an array of parameters and I need to invoke an instance method that should have the most appropriate signature for the invocation, giving the number and type of parameters on my parameter array. The difficulty I'm having finding an answer for this on similar questions on StackOverflow it's because the method I'm targeting has not any specific name; instead, I must select a method from a list of methods that are decorated with a specific Attribute.
Example of a class containing some methods that can be invoked:
public class TestClass
{
[MyAttribute]
public void DoStuff()
{
// Do something
}
[MyAttribute]
public void DoMoreStuff(string msg)
{
// Do something
}
[MyAttribute]
public void DoEvenMoreStuff(string msg, int count, bool isCool = true)
{
// Do Something
}
[MyAttribute]
public void DoEvenMoreStuff(object obj, int count, bool isCool = true)
{
// Do Something
}
}
Now, I need to be able to invoke one of the methods decorated with MyAttribute, but I don't know the name of those methods beforehand. I just need to get all the methods that are decorated with MyAttribute and select one of them based on an array of parameters I already have; and then invoke the selected method.
How should I do to select the best method to be invoked?
You probably want to use Binder.SelectMethod on the default binder (Type.DefaultBinder). This will handle standard implicit conversions (e.g. to base types, interfaces, or object) as well as some numeric conversions (e.g. int to double and long). See the documentation for a more thorough description. This will not match on optional/default parameters. So if you pass string and int it will not match the 3rd method in your example with a default value for the third boolean parameter. Note you may also want to handle the AmbiguousMatchException which is thrown when more than one candidate method could be selected. A short demonstration of its use:
static void Main(string[] args)
{
var methods = typeof(TestClass).GetMethods()
.Where(mi => mi.GetCustomAttributes(true).OfType<MyAttribute>().Any()).ToArray();
var flags = BindingFlags.Default; // I did not see a difference with BindingFlags.OptionalParamBinding;
Type[][] cases = {
new Type[0],
new[] { typeof(string) },
new[] { typeof(string), typeof(int) },
new[] { typeof(string), typeof(int), typeof(bool) },
new[] { typeof(int), typeof(int), typeof(bool) }
};
foreach (var typeCase in cases)
{
string desc = "(" + string.Join(",", typeCase.Select(t => t?.Name ?? "<null>")) + ")";
var method = Type.DefaultBinder.SelectMethod(flags, methods, typeCase, null);
string result = method?.ToString() ?? "No matching method found";
Console.WriteLine($"{desc} -> {result}");
}
}
Output:
() -> Void DoStuff()
(String) -> Void DoMoreStuff(System.String)
(String,Int32) -> No matching method found
(String,Int32,Boolean) -> Void DoEvenMoreStuff(System.String, Int32, Boolean)
(Int32,Int32,Boolean) -> Void DoEvenMoreStuff(System.Object, Int32, Boolean)
I'm not sure if i exactly understand you, (and if i do) you are obviously aware of the serious flaws this approach has
However, for academic purposes only. You could do something like this
var argList = new object[] {"asd", 123, true };
var argTypes = argList.Select(x => x.GetType())
.ToList();
var testClass = new TestClass();
var method = testClass.GetType()
.GetMethods()
.Where(m => m.GetCustomAttributes(typeof(MyAttribute), false)
.Length > 0)
.FirstOrDefault(x => x.GetParameters()
.Select(y => y.ParameterType)
.SequenceEqual(argTypes));
if (method != null)
{
method.Invoke(testClass, argList);
}
Demo here
As stated a better approach would be to use
Binder.SelectMethod Method (BindingFlags, MethodBase[], Type[], ParameterModifier[])
Selects a method from the given set of methods, based on the argument
type.
I am trying to construct some objects in a reasonably generic way. Some of the objects have constructor params, others don't.
What I am trying to achieve is to return some kind of builder function to which I can supply the constructor param if required.
I know I could have optional params passed down, but in my real scenario, there are several layers and I'm loathed to add optional params down the hierarchy.
I'm not too up on partial application/currying, but could I use that here and if so, how?
Here's a bit of sample code - which won't work - to try and explain a bit more what I'm after.
public void Main()
{
dynamic buildClass = ClassBuilder<BaseClass>(true);
// ideally I'd like to be able to supply the constructor data
// here
var theClass = buildClass(???)
}
public Func<???, TClass> ClassBuilder<TClass>(bool flag) where TClass : BaseClass
{
// obviously this won't work since the delegates have different
// signatures
if (flag) return () => GetClassA();
return (x) => GetClassB(x);
}
public object GetClassA()
{
return new ClassA();
}
public object GetClassB(string param)
{
return new ClassB(param);
}
public class BaseClass {}
public class ClassA : BaseClass {}
public class ClassB : BaseClass
{
private string _param;
public ClassB(string param)
{
_param = param;
}
}
Many thx
S
To elaborate #Sylwekqaz you could have something like below, and not restrict yourself for type of BaseClass.
public static class Builder
{
public static T Build<T>(params object[] args) where T : class
{
var info = typeof(T).GetConstructor(args.Select(arg => arg.GetType()).ToArray());
if (info == null)
throw new ArgumentException(#"Can't get constructor :(", "args");
return (T)info.Invoke(args.ToArray());
}
}
And then you can call your builder as
var a = Builder.Build<ClassA>();
var b = Builder.Build<ClassB>(); // need parameterless ctor in ClassB
var c = Builder.Build<ClassB>("param");
You must use code reflection to detect constructor/method with you parameters and invoke it.
Type type = typeof(YourClass);
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
object instance = ctor.Invoke(new object[] { 10 });
~source: Using C# reflection to call a constructor
alternatively you have a class MethodInfo if you must use methods GetClassX
More info
https://msdn.microsoft.com/en-us/library/system.type.getconstructor%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/system.reflection.constructorinfo.invoke%28v=vs.110%29.aspx
I don't entirely follow your code example, but you ask about partial-application and currying...
The best way I've found is to just create N functions that take from 1-N generic parameters, then let the compiler pick the one you want. If you take a look at my language-ext project I have two functions, one called curry and one called par for currying and partial application:
Currying source
Partial application source
To partially apply, do this:
// Example function
int AddFour(int a,int b,int c, int d)
{
return a + b + c + d;
}
// This returns a Func<int,int,int> with the first two arguments 10 & 5 auto-provided
var tenfive = par(AddFour, 10, 5);
// res = 10 + 5 + 1 + 2
var res = tenfive(1,2);
To curry, do this:
// Example function
int AddFour(int a,int b,int c, int d)
{
return a + b + c + d;
}
// Returns Func<int,Func<int,Func<int,Func<int,int>>>>
var f = curry(AddFour);
// res = 10 + 5 + 1 + 2
var res = f(10)(5)(1)(2);
I'd like to use reflection on a certain type argument T to get its constructors.
The constructors i'd like to get are ones that accept certain Type ISomeType, or any type derived from it.
For example:
public interface ISomeType
{
}
public class SomeClass : ISomeType
{
}
I'd like to find constructors that either accept ISomeType, SomeClass, or any other ISomeType derived class.
Is there any easy way of achieving this?
You could do something like this:
public List<ConstructorInfo> GetConstructors(Type type, Type baseParameterType)
{
List<ConstructorInfo> result = new List<ConstructorInfo>();
foreach (ConstructorInfo ci in type.GetConstructors())
{
var parameters = ci.GetParameters();
if (parameters.Length != 1)
continue;
ParameterInfo pi = parameters.First();
if (!baseParameterType.IsAssignableFrom(pi.ParameterType))
continue;
result.Add(ci);
}
return result;
}
which is equivalent with
public IEnumerable<ConstructorInfo> GetConstructors(Type type, Type baseParameterType)
{
return type.GetConstructors()
.Where(ci => ci.GetParameters().Length == 1)
.Where(ci => baseParameterType.IsAssignableFrom(ci.GetParameters().First().ParameterType)
}
when you add some LINQ magic
You can do it like this:
Type myType = ...
var constrs = myType
.GetConstructors()
.Where(c => c.GetParameters().Count()==1
&& c.GetParameters()[0].ParameterType.GetInterfaces().Contains(typeof(ISomeType))
).ToList();
if (constrs.Count == 0) {
// No constructors taking a class implementing ISomeType
} else if (constrs.Count == 1) {
// A single constructor taking a class implementing ISomeType
} else {
// Multiple constructors - you may need to go through them to decide
// which one you would prefer to use.
}
base class doesn't know about own devived classes, that's why you can't get derived class's ctors. you must get all classes from assembly and find accept ctors among them
I am wondering what it would take to make something like this work:
using System;
class Program
{
static void Main()
{
var f = new IFoo {
Foo = "foo",
Print = () => Console.WriteLine(Foo)
};
}
}
interface IFoo
{
String Foo { get; set; }
void Print();
}
The anonymous type created would look something like this:
internal sealed class <>f__AnonymousType0<<Foo>j__TPar> : IFoo
{
readonly <Foo>j__TPar <Foo>i__Field;
public <>f__AnonymousType0(<Foo>j__TPar Foo)
{
this.<Foo>i__Field = Foo;
}
public <Foo>j__TPar Foo
{
get { return this.<Foo>i__Field; }
}
public void Print()
{
Console.WriteLine(this.Foo);
}
}
Is there any reason that the compiler would be unable to do something like this? Even for non-void methods or methods that take parameters the compiler should be able to infer the types from the interface declaration.
Disclaimer: While I do realize that this is not currently possible and it would make more sense to simply create a concrete class in this instance I am more interested in the theoretical aspects of this.
There would be a few issues with overloaded members, indexers, and explicit interface implementations.
However, you could probably define the syntax in a way that allows you to resolve those problems.
Interestingly, you can get pretty close to what you want with C# 3.0 by writing a library. Basically, you could do this:
Create<IFoo>
(
new
{
Foo = "foo",
Print = (Action)(() => Console.WriteLine(Foo))
}
);
Which is pretty close to what you want. The primary differences are a call to "Create" instead of the "new" keyword and the fact that you need to specify a delegate type.
The declaration of "Create" would look like this:
T Create<T> (object o)
{
//...
}
It would then use Reflection.Emit to generate an interface implementation dynamically at runtime.
This syntax, however, does have problems with explicit interface implementations and overloaded members, that you couldn't resolve without changing the compiler.
An alternative would be to use a collection initializer rather than an anonymous type. That would look like this:
Create
{
new Members<IFoo>
{
{"Print", ((IFoo #this)=>Console.WriteLine(Foo))},
{"Foo", "foo"}
}
}
That would enable you to:
Handle explicit interface implementation by specifying something like "IEnumerable.Current" for the string parameter.
Define Members.Add so that you don't need to specify the delegate type in the initializer.
You would need to do a few things to implement this:
Writer a small parser for C# type names. This only requires ".", "[]", "<>",ID, and the primitive type names, so you could probably do that in a few hours
Implement a cache so that you only generate a single class for each unique interface
Implement the Reflection.Emit code gen. This would probably take about 2 days at the most.
It requires c# 4, but the opensource framework impromptu interface can fake this out of the box using DLR proxies internally. The performance is good although not as good as if the change you proposed existed.
using ImpromptuInterface.Dynamic;
...
var f = ImpromptuGet.Create<IFoo>(new{
Foo = "foo",
Print = ReturnVoid.Arguments(() => Console.WriteLine(Foo))
});
An anonymous type can't be made to do anything except to have read-only properties.
Quoting the C# Programming Guide (Anonymous Types):
"Anonymous types are class types that
consist of one or more public
read-only properties. No other kinds
of class members such as methods or
events are allowed. An anonymous type
cannot be cast to any interface or
type except for object."
As long as we're putting out an interface wish list, I'd really like to be able to tell the compiler that a class implements an interface outside the class definition- even in a separate assembly.
For example, let's say I'm working on a program to extract files from different archive formats. I want to be able to pull in existing implementations from different libraries — say, SharpZipLib and a commercial PGP implementation — and consume both libraries using the same code without creating new classes. Then I could use types from either source in generic constraints, for example.
Another use would be telling the compiler that System.Xml.Serialization.XmlSerializer implements the System.Runtime.Serialization.IFormatter interface (it already does, but the compiler doesn't know it).
This could be used to implement your request as well, just not automatically. You'd still have to explicitly tell the compiler about it. Not sure how the syntax would look, because you'd still have to manually map methods and properties somewhere, which means a lot of verbiage. Maybe something similar to extension methods.
You could have something like anonymous classes in Java:
using System;
class Program {
static void Main() {
var f = new IFoo() {
public String Foo { get { return "foo"; } }
public void Print() { Console.WriteLine(Foo); }
};
}
}
interface IFoo {
String Foo { get; set; }
void Print();
}
Wouldn't this be cool. Inline anonymous class:
List<Student>.Distinct(new IEqualityComparer<Student>()
{
public override bool Equals(Student x, Student y)
{
return x.Id == y.Id;
}
public override int GetHashCode(Student obj)
{
return obj.Id.GetHashCode();
}
})
I'm going to dump this here. I wrote it a while ago but IIRC it works OK.
First a helper function to take a MethodInfo and return a Type of a matching Func or Action. You need a branch for each number of parameters, unfortunately, and I apparently stopped at three.
static Type GenerateFuncOrAction(MethodInfo method)
{
var typeParams = method.GetParameters().Select(p => p.ParameterType).ToArray();
if (method.ReturnType == typeof(void))
{
if (typeParams.Length == 0)
{
return typeof(Action);
}
else if (typeParams.Length == 1)
{
return typeof(Action<>).MakeGenericType(typeParams);
}
else if (typeParams.Length == 2)
{
return typeof(Action<,>).MakeGenericType(typeParams);
}
else if (typeParams.Length == 3)
{
return typeof(Action<,,>).MakeGenericType(typeParams);
}
throw new ArgumentException("Only written up to 3 type parameters");
}
else
{
if (typeParams.Length == 0)
{
return typeof(Func<>).MakeGenericType(typeParams.Concat(new[] { method.ReturnType }).ToArray());
}
else if (typeParams.Length == 1)
{
return typeof(Func<,>).MakeGenericType(typeParams.Concat(new[] { method.ReturnType }).ToArray());
}
else if (typeParams.Length == 2)
{
return typeof(Func<,,>).MakeGenericType(typeParams.Concat(new[] { method.ReturnType }).ToArray());
}
else if (typeParams.Length == 3)
{
return typeof(Func<,,,>).MakeGenericType(typeParams.Concat(new[] { method.ReturnType }).ToArray());
}
throw new ArgumentException("Only written up to 3 type parameters");
}
}
And now the method that takes an interface as a generic parameter and returns a Type that implements the interface and has a constructor (needs to be called via Activator.CreateInstance) taking a Func or Action for each method/ getter/setter. You need to know the right order to put them in the constructor, though. Alternatively (commented-out code) it can generate a DLL which you can then reference and use the type directly.
static Type GenerateInterfaceImplementation<TInterface>()
{
var interfaceType = typeof(TInterface);
var funcTypes = interfaceType.GetMethods().Select(GenerateFuncOrAction).ToArray();
AssemblyName aName =
new AssemblyName("Dynamic" + interfaceType.Name + "WrapperAssembly");
var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.Run/*AndSave*/); // to get a DLL
var modBuilder = assBuilder.DefineDynamicModule(aName.Name/*, aName.Name + ".dll"*/); // to get a DLL
TypeBuilder typeBuilder = modBuilder.DefineType(
"Dynamic" + interfaceType.Name + "Wrapper",
TypeAttributes.Public);
// Define a constructor taking the same parameters as this method.
var ctrBuilder = typeBuilder.DefineConstructor(
MethodAttributes.Public | MethodAttributes.HideBySig |
MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
CallingConventions.Standard,
funcTypes);
// Start building the constructor.
var ctrGenerator = ctrBuilder.GetILGenerator();
ctrGenerator.Emit(OpCodes.Ldarg_0);
ctrGenerator.Emit(
OpCodes.Call,
typeof(object).GetConstructor(Type.EmptyTypes));
// For each interface method, we add a field to hold the supplied
// delegate, code to store it in the constructor, and an
// implementation that calls the delegate.
byte methodIndex = 0;
foreach (var interfaceMethod in interfaceType.GetMethods())
{
ctrBuilder.DefineParameter(
methodIndex + 1,
ParameterAttributes.None,
"del_" + interfaceMethod.Name);
var delegateField = typeBuilder.DefineField(
"del_" + interfaceMethod.Name,
funcTypes[methodIndex],
FieldAttributes.Private);
ctrGenerator.Emit(OpCodes.Ldarg_0);
ctrGenerator.Emit(OpCodes.Ldarg_S, methodIndex + 1);
ctrGenerator.Emit(OpCodes.Stfld, delegateField);
var metBuilder = typeBuilder.DefineMethod(
interfaceMethod.Name,
MethodAttributes.Public | MethodAttributes.Virtual |
MethodAttributes.Final | MethodAttributes.HideBySig |
MethodAttributes.NewSlot,
interfaceMethod.ReturnType,
interfaceMethod.GetParameters()
.Select(p => p.ParameterType).ToArray());
var metGenerator = metBuilder.GetILGenerator();
metGenerator.Emit(OpCodes.Ldarg_0);
metGenerator.Emit(OpCodes.Ldfld, delegateField);
// Generate code to load each parameter.
byte paramIndex = 1;
foreach (var param in interfaceMethod.GetParameters())
{
metGenerator.Emit(OpCodes.Ldarg_S, paramIndex);
paramIndex++;
}
metGenerator.EmitCall(
OpCodes.Callvirt,
funcTypes[methodIndex].GetMethod("Invoke"),
null);
metGenerator.Emit(OpCodes.Ret);
methodIndex++;
}
ctrGenerator.Emit(OpCodes.Ret);
// Add interface implementation and finish creating.
typeBuilder.AddInterfaceImplementation(interfaceType);
var wrapperType = typeBuilder.CreateType();
//assBuilder.Save(aName.Name + ".dll"); // to get a DLL
return wrapperType;
}
You can use this as e.g.
public interface ITest
{
void M1();
string M2(int m2, string n2);
string prop { get; set; }
event test BoopBooped;
}
Type it = GenerateInterfaceImplementation<ITest>();
ITest instance = (ITest)Activator.CreateInstance(it,
new Action(() => {Console.WriteLine("M1 called"); return;}),
new Func<int, string, string>((i, s) => "M2 gives " + s + i.ToString()),
new Func<String>(() => "prop value"),
new Action<string>(s => {Console.WriteLine("prop set to " + s);}),
new Action<test>(eh => {Console.WriteLine(eh("handler added"));}),
new Action<test>(eh => {Console.WriteLine(eh("handler removed"));}));
// or with the generated DLL
ITest instance = new DynamicITestWrapper(
// parameters as before but you can see the signature
);
Interesting idea, I'd be a little concerned that even if it could be done it might get confusing. E.g. when defining a property with non-trivial setters and getters, or how to disambiguate Foo if the the declaring type also contained a property called Foo.
I wonder if this would be easier in a more dynamic language, or even with the dynamic type and DLR in C# 4.0?
Perhaps today in C# some of the intent could be achieved with lambdas:
void Main() {
var foo = new Foo();
foo.Bar = "bar";
foo.Print = () => Console.WriteLine(foo.Bar);
foo.Print();
}
class Foo : IFoo {
public String Bar { get; set; }
public Action Print {get;set;}
}
This wouldn't be possible currently.
What would be the difference between this and simply making IFoo a concrete class instead? Seems like that might be the better option.
What it would take? A new compiler and tons of checks to ensure they didn't break the other features. Personally, I think it'd just be easier to require developers to just create a concrete version of their class.
I have used in Java the Amonimous Class through the "new IFoo(){...}" sintax and it's practical and easy when you have to quick implement a simple interface.
As a sample it would be nice to implement IDisposable this way on a legacy object used just one time instead of deriving a new class to implement it.