Search Results

Search found 1008 results on 41 pages for 'generics'.

Page 17/41 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • .NET template class instance - passing a variable data type

    - by FerretallicA
    As the title suggests, I'm tyring to pass a variable data type to a template class. Something like this: frmExample = New LookupForm(Of Models.MyClass) 'Works fine Dim SelectedType As Type = InstanceOfMyClass.GetType() 'Works fine frmExample = New LookupForm(Of SelectedType) 'Ba-bow! frmExample = New LookupForm(Of InstanceOfMyClass.GetType()) 'Ba-bow! LookupForm<Models.MyClass> frmExample; Type SelectedType = InstanceOfMyClass.GetType(); frmExample = new LookupForm<SelectedType.GetType()>(); //Ba-bow frmExample = new LookupForm<(Type)SelectedType>(); //Ba-bow I'm assuming it's something to do with the template being processed at compile time but even if I'm off the mark there, it wouldn't solve my problem anyway. I can't find any relevant information on using Reflection to instance template classes either. (How) can I create an instance of a dynamically typed repository at runtime?

    Read the article

  • Retrieving the type of a Collection

    - by nevets1219
    So I have something like the following in Java: private List<SomeType>variable; // ....variable is instantiated as so ... variable = new ArrayList<SomeType>(); // there's also a getter public List<SomeType> getVariable() { /* code */ } What I would like to be able to do is figure out that variable is a collection of SomeType programmatically. I read here that I can determine that from the method getVariable() but is there any way to tell directly from variable? I have been able to retrieve SomeType from the getter method based on the information in the link. I have also been successful in retrieving all the fields of the surrounding class via SurroundingClass.getClass().getDeclaredFields() but this doesn't tell me that it is List<SomeType>.

    Read the article

  • Java generic Comparable where subclasses can't compare to eachother

    - by dege
    public abstract class MyAbs implements Comparable<MyAbs> This would work but then I would be able to compare class A and B with each other if they both extend MyAbs. What I want to accomplish however is the exact opposite. So does anyone know a way to get the generic type to be the own class? Seemed like such a simple thing at first... Edit: To explain it a little further with an example. Say you have an abstract class animals, then you extend it with Dogs and ants. I wouldn't want to compare ants with Dogs but I however would want to compare one dog with another. The dog might have a variable saying what color it is and that is what I want to use in the compareTo method. However when it comes to ants I would rather want to compare ant's size than their color. Hope that clears it up. Could possibly be a design flaw however.

    Read the article

  • Java class object from type variable

    - by Alexander Temerev
    Is there a way to get Class object from the type variable in Java generic class? Something like that: public class Bar extends Foo<T> { public Class getParameterClass() { return T.class; // doesn't compile } } This type information is available at compile time and therefore should not be affected by type erasure, so, theoretically, there should be a way to accomplish this. Does it exist?

    Read the article

  • How to Create a Generic Method and Create Instance of The Type

    - by DaveDev
    Hi Guys I want to create a helper method that I can imagine has a signature similar to this: public static MyHtmlTag GenerateTag<T>(this HtmlHelper htmlHelper, object obj) { // how do I create an instance of MyAnchor? // this returns MyAnchor, which has a MyHtmlTag base } When I invoke the method, I want to specify a type of MyHtmlTag, such as MyAnchor, e.g.: <%= Html.GenerateTag<MyAnchor>(obj) %> or <%= Html.GenerateTag<MySpan>(obj) %> Can someone show me how to create this method? Also, what's involved in creating an instance of the type I specified? Activator.CreateInstance()? Thanks Dave

    Read the article

  • How to Pass Parameters to Activator.CreateInstance<T>()

    - by DaveDev
    Hi guys I want to create an instance of a type that I specify in a generic method that I have. This type has a number of overloaded constructors. I'd like to be able to pass arguments to the constructors, but Activator.CreateInstance<T>() doesn't see to have this as an option. Is there another way to do it? Thanks Dave

    Read the article

  • Is there a way to make ToEnum generic

    - by maxfridbe
    I would like to do this but it does not work. bool TryGetEnum<TEnum, TValue>(TValue value, out TEnum myEnum) { if (Enum.IsDefined(typeof(TEnum), value)) { myEnum = (TEnum)value; return true; } return false; } Example usage: MyEnum mye; bool success = this.TryGetEnum<MyEnum,char>('c',out mye);

    Read the article

  • What would be the best .NET 2.0 type to represent .NET 3.5 HashSet<T>?

    - by Will Marcouiller
    I'm writing myself a class library to manage Active Directory. I have an interface: Public Interface ISourceAnnuaire(Of T as {IGroupe, ITop, IUniteOrganisation, IUtilisateur}) Readonly Property Changements As Dictionary(Of T, HashSet(Of String)) End Interface This Changements property is used to save in memory the changes that occur on a particular element that is part of the source. However, I am stuck with .NET Framework 2.0. What would be the closest .NET 2.0 for HashSet(Of String)?

    Read the article

  • Discover generic types

    - by vittore
    Thanks @dtb for help, he advised really need piece of code for generic service locator static class Locator { private static class LocatorEntry<T> where T : ... { public static IDataManager<T> instance; } public static void Register<T>(IDataManager<T> instance) where T : ... { LocatorEntry<T>.instance = instance; } public static IDataManager<T> GetInstance<T>() where T : ... { return LocatorEntry<T>.instance; } } However in my previous version I used reflection on assembly to discover a hundred of DataManager's I want to write an method discover like the following void Discover() { var pManager = new ProtocolSQLDataManager(); Register(pManager); var rManager = new ResultSQLDataManager(); Register(rManager); var gType = typeof(ISQLDataAccessManager<>); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { if (type.IsSubclassOf(gType) && !type.IsAbstract)) { var manager = Activator.CreateInstance(type); // put something here in order to make next line of code works Register<T>(manager); } } } How to cast type to appropriate type in order to make Register working( and call appropriate Register ?

    Read the article

  • Setting generic type at runtime

    - by destroyer of evil
    I have a class public class A<T> { public static string B(T obj) { return TransformThisObjectToAString(obj); } } I can call the static function like this just fine on a known/specified type: string s= A<KnownType>.B(objectOfKnownType); How do I make this call, if I don't know T beforehand, rather I have a variable of type Type that holds the type. If I do this: Type t= typeof(string); string s= A<t>.B(someStringObject); I get this compiler error: Cannot implicitly convert type 't' to 'object'

    Read the article

  • Compilers behave differently with a null parameter of a generic method

    - by Eyal Schneider
    The following code compiles perfectly with Eclipse, but fails to compile with javac: public class HowBizarre { public static <P extends Number, T extends P> void doIt(P value) { } public static void main(String[] args) { doIt(null); } } I simplified the code, so T is not used at all now. Still, I don't see a reason for the error. For some reason javac decides that T stands for Object, and then complains that Object does not conform to the bounds of T (which is true): HowBizarre.java:6: incompatible types; inferred type argument(s) java.lang.Number,java.lang.Object do not conform to bounds of type variable (s) P,T found : <P,T>void required: void doIt(null); ^ Note that if I replace the null parameter with a non-null value, it compiles fine. Which of the compilers behaves correctly and why? Is this a bug of one of them?

    Read the article

  • Calling a method with an instance of derived class of derived generic type

    - by madsbirk
    Okay, so I have classes class B<T> : A<T> class L : K and a method void Method(A<K> a) {...} What I would like to do is this b = new B<L>(); Method(b); //error But it is not possible to b to the correct type. Indeed it is not possible to make this cast A<K> t = new A<L>(); //error I would really like to not have to change the internals of Method. I have no problems making changes to B and/or L. Do I have any options for making some sort of workaround? I guess it should be possible for Method to execute all of its method calls etc. on b, since B derives from A and L derives from K?

    Read the article

  • Implementing IComparer<T> For IComparer<DictionaryEntry>

    - by Phil Sandler
    I am using the ObservableSortedDictionary from Dr. WPF. The constructor looks like this: public ObservableSortedDictionary(IComparer<DictionaryEntry> comparer) I am really struggling to create an implementation that satisfies the constructor and works. My current code (that won't compile) is: public class TimeCreatedComparer<T> : IComparer<T> { public int Compare(T x, T y) { var myclass1 = (IMyClass)((DictionaryEntry)x).Value; var myclass2 = (IMyClass)((DictionaryEntry)y).Value; return myclass1.TimeCreated.CompareTo(myclass2.TimeCreated); } } It says I can't cast from T to DictionaryEntry. If I cast directly to IMyClass, it compiles, but I get a runtime error saying I can't cast from DictionaryEntry to IMyClass. At runtime, x and y are instances of DictionaryEntry, which each have the correct IMyClass as their Value.

    Read the article

  • How to perform a binary search on IList<T>?

    - by Daniel Brückner
    Simple question - given an IList<T> how do you perform a binary search without writing the method yourself and without copying the data to a type with build-in binary search support. My current status is the following. List<T>.BinarySearch() is not a member of IList<T> There is no equivalent of the ArrayList.Adapter() method for List<T> IList<T> does not inherit from IList, hence using ArrayList.Adapter() is not possible I tend to believe that is not possible with build-in methods, but I cannot believe that such a basic method is missing from the BCL/FCL. If it is not possible, who can give the shortest, fastest, smartest, or most beatiful binary search implementation for IList<T>? UPDATE We all know that a list must be sorted before using binary search, hence you can assume that it is. But I assume (but did not verify) it is the same problem with sort - how do you sort IList<T>? CONCLUSION There seems to be no build-in binary search for IList<T>. One can use First() and OrderBy() LINQ methods to search and sort, but it will likly have a performance hit. Implementing it yourself (as an extension method) seems the best you can do.

    Read the article

  • How do I assert that two arbitrary type objects are equivalent, without requiring them to be equal?

    - by Tomas Lycken
    To accomplish this (but failing to do so) I'm reflecting over properties of an expected and actual object and making sure their values are equal. This works as expected as long as their properties are single objects, i.e. not lists, arrays, IEnumerable... If the property is a list of some sort, the test fails (on the Assert.AreEqual(...) inside the for loop). public void WithCorrectModel<TModelType>(TModelType expected, string error = "") where TModelType : class { var actual = _result.ViewData.Model as TModelType; Assert.IsNotNull(actual, error); Assert.IsInstanceOfType(actual, typeof(TModelType), error); foreach (var prop in typeof(TModelType).GetProperties()) { Assert.AreEqual(prop.GetValue(expected, null), prop.GetValue(actual, null), error); } } If dealing with a list property, I would get the expected results if I instead used CollectionAssert.AreEquivalent(...) but that requires me to cast to ICollection, which in turn requries me to know the type listed, which I don't (want to). It also requires me to know which properties are list types, which I don't know how to. So, how should I assert that two objects of an arbitrary type are equivalent? Note: I specifically don't want to require them to be equal, since one comes from my tested object and one is built in my test class to have something to compare with.

    Read the article

  • Why does this work?

    - by Fizz
    Why does this work? I'm not complaining, just want to know. void Test() { int a = 1; int b = 2; What<int>(a, b); // Why does this next line work? What(a, b); } void What<T>(T a, T b) { }

    Read the article

  • Class hierarchy problem (with generic's variance!)

    - by devoured elysium
    The problem: class StatesChain : IState, IHasStateList { private TasksChain tasks = new TasksChain(); ... public IList<IState> States { get { return _taskChain.Tasks; } } IList<ITask> IHasTasksCollection.Tasks { get { return _taskChain.Tasks; } <-- ERROR! You can't do this in C#! I want to return an IList<ITask> from an IList<IStates>. } } Assuming the IList returned will be read-only, I know that what I'm trying to achieve is safe (or is it not?). Is there any way I can accomplish what I'm trying? I wouldn't want to try to implement myself the TasksChain algorithm (again!), as it would be error prone and would lead to code duplication. Maybe I could just define an abstract Chain and then implement both TasksChain and StatesChain from there? Or maybe implementing a Chain<T> class? How would you approach this situation? The Details: I have defined an ITask interface: public interface ITask { bool Run(); ITask FailureTask { get; } } and a IState interface that inherits from ITask: public interface IState : ITask { IState FailureState { get; } } I have also defined an IHasTasksList interface: interface IHasTasksList { List<Tasks> Tasks { get; } } and an IHasStatesList: interface IHasTasksList { List<Tasks> States { get; } } Now, I have defined a TasksChain, that is a class that has some code logic that will manipulate a chain of tasks (beware that TasksChain is itself a kind of ITask!): class TasksChain : ITask, IHasTasksList { IList<ITask> tasks = new List<ITask>(); ... public List<ITask> Tasks { get { return _tasks; } } ... } I am implementing a State the following way: public class State : IState { private readonly TaskChain _taskChain = new TaskChain(); public State(Precondition precondition, Execution execution) { _taskChain.Tasks.Add(precondition); _taskChain.Tasks.Add(execution); } public bool Run() { return _taskChain.Run(); } public IState FailureState { get { return (IState)_taskChain.Tasks[0].FailureTask; } } ITask ITask.FailureTask { get { return FailureState; } } } which, as you can see, makes use of explicit interface implementations to "hide" FailureTask and instead show FailureState property. The problem comes from the fact that I also want to define a StatesChain, that inherits both from IState and IHasStateList (and that also imples ITask and IHasTaskList, implemented as explicit interfaces) and I want it to also hide IHasTaskList's Tasks and only show IHasStateList's States. (What is contained in "The problem" section should really be after this, but I thought puting it first would be way more reader friendly). (pff..long text) Thanks!

    Read the article

  • C#: How to remove items from the collection of a IDictionary<E, ICollection<T>> with LINQ?

    - by Rosarch
    Here is what I am trying to do: private readonly IDictionary<float, ICollection<IGameObjectController>> layers; foreach (ICollection<IGameObjectController> layerSet in layers.Values) { foreach (IGameObjectController controller in layerSet) { if (controller.Model.DefinedInVariant) { layerSet.Remove(controller); } } } Of course, this doesn't work, because it will cause a concurrent modification exception. (Is there an equivalent of Java's safe removal operation on some iterators?) How can I do this correctly, or with LINQ?

    Read the article

  • VS2010 Implement Generic Interface expansion doesn't use specified type

    - by TJB
    Using the release version of Visual Studio 2010 I think there's a difference in the "Implement Interface" expansion from VS2008 If I speicify an interface and implement it in a class as so: public interface IRepository<T> where T : IModel { T Get<T>(int id); void Update<T>(); int Add<T>(T item); } public class MockRepository : IRepository<MockUser> { // ... } Then use the "Implement Interface" expansion and get this: public class MockRepository : IRepository<MockUser> { public T Get<T>(int id) { throw new NotImplementedException(); } public void Update<T>() { throw new NotImplementedException(); } public int Add<T>(T item) { throw new NotImplementedException(); } } Instead of what I expected public class MockRepository : IRepository<MockUser> { public MockUser Get<MockUser>(int id) { throw new NotImplementedException(); } public void Update<MockUser>() { throw new NotImplementedException(); } public int Add<MockUser>(MockUser item) { throw new NotImplementedException(); } } The IDE uses the type variable name from the generic interface definition T instead of the specified concrete type MockUser. Is this a bug? Or is something new just for VS2010 / .Net 4.0?

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >