Search Results

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

Page 8/41 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • C#: Non-constructed generics as properties (eg. List<T>)

    - by Dav
    The Problem It's something I came across a while back and was able to work around it somehow. But now it came back, feeding on my curiosity - and I'd love to have a definite answer. Basically, I have a generic dgv BaseGridView<T> : DataGridView where T : class. Constructed types based on the BaseGridView (such as InvoiceGridView : BaseGridView<Invoice>) are later used in the application to display different business objects using the shared functionality provided by BaseGridView (like virtual mode, buttons, etc.). It now became necessary to create a user control that references those constructed types to control some of the shared functionality (eg. filtering) from BaseGridView. I was therefore hoping to create a public property on the user control that would enable me to attach it to any BaseGridView in Designer/code: public BaseGridView<T> MyGridView { get; set; }. The trouble is, it doesn't work :-) When compiled, I get the following message: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) Solutions? I realise I could extract the shared functionality to an interface, mark BaseGridView as implementing that interface, and then refer to the created interface in my uesr control. But I'm curious if there exists some arcane C# command/syntax that would help me achieve what I want - without polluting my solution with an interface I don't really need :-)

    Read the article

  • Is is possible to do an end-run around generics covariance in C# < 4 in this hypothetical situation?

    - by John Feminella
    Suppose I have a small inheritance hierarchy of Animals: public interface IAnimal { string Speak(); } public class Animal : IAnimal { public Animal() {} public string Speak() { return "[Animal] Growl!"; } } public class Ape : IAnimal { public string Speak() { return "[Ape] Rawrrrrrrr!"; } } public class Bat : IAnimal { public string Speak() { return "[Bat] Screeeeeee!"; } } Next, here's an interface offering a way to turn strings into IAnimals. public interface ITransmogrifier<T> where T : IAnimal { T Transmogrify(string s); } And finally, here's one strategy for doing that: public class Transmogrifier<T> : ITransmogrifier<T> where T : IAnimal, new() { public T Transmogrify(string s) { T t = default(T); if (typeof(T).Name == s) t = new T(); return t; } } Now, the question. Is it possible to replace the sections marked [1], [2], and [3] such that this program will compile and run correctly? If you can't do it without touching parts other than [1], [2], and [3], can you still get an IAnimal out of each instance of a Transmogrifier in a collection containing arbitrary implementations of an IAnimal? Can you even form such a collection to begin with? static void Main(string[] args) { var t = new Transmogrifier<Ape>(); Ape a = t.Transmogrify("Ape"); Console.WriteLine(a.Speak()); // Works! // But can we make an arbitrary collection of such animals? var list = new List<Transmogrifier< [1] >>() { // [2] }; // And how about we call Transmogrify() on each one? foreach (/* [3] */ transmogrifier in list) { IAnimal ia = transmogrifier.Transmogrify("Bat"); } } }

    Read the article

  • How can I make this simple C# generics factory work?

    - by Kevin Brassen
    I have this design: public interface IFactory<T> { T Create(); T CreateWithSensibleDefaults(); } public class AppleFactory : IFactory<Apple> { ... } public class BananaFactory : IFactory<Banana> { ... } // ... The fictitious Apple and Banana here do not necessarily share any common types (other than object, of course). I don't want clients to have to depend on specific factories, so instead, you can just ask a FactoryManager for a new type. It has a FactoryForType method: IFactory<T> FactoryForType<T>(); Now you can invoke the appropriate interface methods with something like FactoryForType<Apple>().Create(). So far, so good. But there's a problem at the implementation level: how do I store this mapping from types to IFactory<T>s? The naive answer is an IDictionary<Type, IFactory<T>>, but that doesn't work since there's no type covariance on the T (I'm using C# 3.5). Am I just stuck with an IDictionary<Type, object> and doing the casting manually?

    Read the article

  • How to avoid Eclipse warnings when using legacy code without generics?

    - by Paul Crowley
    I'm using JSON.simple to generate JSON output from Java. But every time I call jsonobj.put("this", "that"), I see a warning in Eclipse: Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized The clean fix would be if JSONObject were genericized, but since it isn't, I can't add any generic type parameters to fix this. I'd like to switch off as few warnings as possible, so adding "@SuppressWarnings("unchecked")" to lots of methods is unappealing, but do I have any other option besides putting up with the warnings?

    Read the article

  • How to call a generic method with an anonymous type involving generics?

    - by Alex Black
    I've got this code that works: def testTypeSpecialization = { class Foo[T] def add[T](obj: Foo[T]): Foo[T] = obj def addInt[X <% Foo[Int]](obj: X): X = { add(obj) obj } val foo = addInt(new Foo[Int] { def someMethod: String = "Hello world" }) assert(true) } But, I'd like to write it like this: def testTypeSpecialization = { class Foo[T] def add[X, T <% Foo[X](obj: T): T = obj val foo = add(new Foo[Int] { def someMethod: String = "Hello world" }) assert(true) } This second one fails to compile: no implicit argument matching parameter type (Foo[Int]{ ... }) = Foo[Nothing] was found. Basically: I'd like to create a new anonymous class/instance on the fly (e.g. new Foo[Int] { ... } ), and pass it into an "add" method which will add it to a list, and then return it The key thing here is that the variable from "val foo = " I'd like its type to be the anonymous class, not Foo[Int], since it adds methods (someMethod in this example) Any ideas? I think the 2nd one fails because the type Int is being erased. I can apparently 'hint' the compiler like this: def testTypeSpecialization = { class Foo[T] def add[X, T <% Foo[X]](dummy: X, obj: T): T = obj val foo = add(2, new Foo[Int] { def someMethod: String = "Hello world" }) assert(true) }

    Read the article

  • Using generics in dotnet for functions with any number of arguments?

    - by Zarigani
    I would like to have a function that can "wrap" any other function call. In this particular case, it would allow me to write some more generic transaction handling around some specific operations. I can write this for any particular number of arguments, e.g. for one argument: Public Shared Sub WrapFunc(Of T)(ByVal f As Action(Of T), ByVal arg As T) ' Test some stuff, start transaction f(arg) ' Test some stuff, end transaction End Sub ... but I was hoping to have this handle any number of arguments without having to have duplicate code for 0 args, 1 arg, 2 args, etc. Is there a way of doing this?

    Read the article

  • How to properly mix generics and inheritance to get the desired result?

    - by yamsha
    My question is not easy to explain using words, fortunately it's not too difficult to demonstrate. So, bear with me: public interface Command<R> { public R execute();//parameter R is the type of object that will be returned as the result of the execution of this command } public abstract class BasicCommand<R> { } public interface CommandProcessor<C extends Command<?>> { public <R> R process(C<R> command);//this is my question... it's illegal to do, but you understand the idea behind it, right? } //constrain BasicCommandProcessor to commands that subclass BasicCommand public class BasicCommandProcessor implements CommandProcessor<C extends BasicCommand<?>> { //here, only subclasses of BasicCommand should be allowed as arguments but these //BasicCommand object should be parameterized by R, like so: BasicCommand<R> //so the method signature should really be // public <R> R process(BasicCommand<R> command) //which would break the inheritance if the interface's method signature was instead: // public <R> R process(Command<R> command); //I really hope this fully illustrates my conundrum public <R> R process(C<R> command) { return command.execute(); } } public class CommandContext { public static void main(String... args) { BasicCommandProcessor bcp = new BasicCommandProcessor(); String textResult = bcp.execute(new BasicCommand<String>() { public String execute() { return "result"; } }); Long numericResult = bcp.execute(new BasicCommand<Long>() { public Long execute() { return 123L; } }); } } Basically, I want the generic "process" method to dictate the type of generic parameter of the Command object. The goal is to be able to restrict different implementations of CommandProcessor to certain classes that implement Command interface and at the same time to able to call the process method of any class that implements the CommandProcessor interface and have it return the object of type specified by the parametarized Command object. I'm not sure if my explanation is clear enough, so please let me know if further explanation is needed. I guess, the question is "Would this be possible to do, at all?" If the answer is "No" what would be the best work-around (I thought of a couple on my own, but I'd like some fresh ideas)

    Read the article

  • Help With Generics? How to Define Generic Method?

    - by DaveDev
    Is it possible to create a generic method with a definition similar to: public static string GenerateWidget<TypeOfHtmlGen, WidgetType>(this HtmlHelper htmlHelper , object modelData) // TypeOfHtmlGenerator is a type that creates custom Html tags. // GenerateWidget creates custom Html tags which contains Html representing the Widget. I can use this method to create any kind of widget contained within any kind of Html tag. Thanks

    Read the article

  • Using runtime generic type reflection to build a smarter DAO

    - by kerry
    Have you ever wished you could get the runtime type of your generic class? I wonder why they didn’t put this in the language. It is possible, however, with reflection: Consider a data access object (DAO) (note: I had to use brackets b/c the arrows were messing with wordpress): public interface Identifiable { public Long getId(); } public interface Dao { public T findById(Long id); public void save(T obj); public void delete(T obj); } Using reflection, we can create a DAO implementation base class, HibernateDao, that will work for any object: import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; public class HibernateDao implements Dao { private final Class clazz; public HibernateDao(Session session) { // the magic ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass(); return (Class) parameterizedType.getActualTypeArguments()[0]; } public T findById(Long id) { return session.get(clazz, id); } public void save(T obj) { session.saveOrUpdate(obj); } public void delete(T obj) { session.delete(obj); } } Then, all we have to do is extend from the class: public class BookDaoHibernateImpl extends HibernateDao { }

    Read the article

  • How to keep a generic process unique?

    - by Steve Van Opstal
    I'm currently working on a project that makes connection between different banks which send us information on which that project replies. A part of that project configures the different protocols that are used (not every bank uses the same protocol), this runs on a separate server. These processes all have unique id's which are stored in a database. But to save time and money on configurations and new processes, we want to make a generic protocol that banks can use. Because of PCI requirements we have to make a separate process for every bank we connect to. But the generic process has only 1 unique identifier and therefor we cannot keep them apart. Giving every copy of that process a different identifier is as I see it impossible because they run entirely separate. So how do I keep my generic process unique?

    Read the article

  • Need advice on framework design: how to make extending easy

    - by beginner_
    I'm creating a framework/library for a rather specific use-case (data type). It uses diverse spring components, including spring-data. The library has a set of entity classes properly set up and according service and dao layers. The main work or main benefit of the framework lies in the dao and service layer. Developers using the framework should be able to extend my entity classes to add additional fields they require. Therefore I made dao and service layer generic so it can be used by such extended entity classes. I now face an issue in the IO part of the framework. It must be able to import the according "special data type" into the database. In this part I need to create a new entity instance and hence need the actual class used. My current solution is to configure in spring a bean of the actual class used. The problem with this is that an application using the framework could only use 1 implementation of the entity (the original one from me or exactly 1 subclass but not 2 different classes of the same hierarchy. I'm looking for suggestions / desgins for solving this issue. Any ideas?

    Read the article

  • generic programming- where did it originate?

    - by user997112
    Im trying to work out if generic programming was a functional programming feature which was then introduced into Java, C++ and C# or did the latter copy it from the functional programming languages like Haskell, Lisp, OCaml etc? Google is giving me lots on what generic programming is, but not where it originated. All I can see is that Ada implemented it early on. Would you class it as a functional programming technique?

    Read the article

  • Who extends interfaces? And why?

    - by Gangnus
    AFAIK, my class extends parent classes and implements interfaces. But I run across a situation, where I can't use implements SomeInterface. It is the declaration of a generic types. For example: public interface CallsForGrow {...} public class GrowingArrayList <T implements CallsForGrow> // BAD, won't work! extends ArrayList<T> Here using implements is syntactically forbidden. I thought first, that using interface inside < is forbidden at all, but no. It is possible, I only have to use extends instead of implements. As a result, I am "extending" an interface. This another example works: public interface CallsForGrow {...} public class GrowingArrayList <T extends CallsForGrow> // this works! extends ArrayList<T> To me it seems as a syntactical inconsistancy. But maybe I don't understand some finesses of Java 6? Are there other places where I should extend interfaces? Should the interface, that I mean to extend, have some special features?

    Read the article

  • Correct usage of "<T extends SuperClass>"

    - by yusaku
    I am not familiar with "Generics". Is it a correct use of "<T extends SuperClass>" ? And do you agree that the codes after using generics are better? Before using Generics ================================================= public abstract class SuperSample { public void getSomething(boolean isProcessA) { doProcessX(); if(isProcessA){ doProcessY(new SubASample()); }else{ doProcessY(new SubBSample()); } } protected abstract void doProcessX(); protected void doProcessY(SubASample subASample) { // Nothing to do } protected void doProcessY(SubBSample subBSample) { // Nothing to do } } public class SubASample extends SuperSample { @Override protected void doProcessX() { System.out.println("doProcessX in SubASample"); } @Override protected void doProcessY(SubASample subASample) { System.out.println("doProcessY in SubASample"); } } public class Sample { public static void main(String[] args) { SubASample subASample = new SubASample(); subASample.getSomething(true); } } After using Generics ================================================= public abstract class SuperSample { public void getSomething(boolean isProcessA) { doProcessX(); if(isProcessA){ doProcessY(new SubASample()); }else{ doProcessY(new SubBSample()); } } protected abstract void doProcessX(); protected abstract <T extends SuperSample> void doProcessY(T subSample); } public class SubASample extends SuperSample { @Override protected void doProcessX() { System.out.println("doProcessX in SubASample"); } @Override protected <T extends SuperSample> void doProcessY(T subSample) { System.out.println("doProcessY in SubASample"); } } public class Sample { public static void main(String[] args) { SubASample subASample = new SubASample(); subASample.getSomething(true); } }

    Read the article

  • Generics vs Object performance

    - by Risho
    I'm doing practice problems from MCTS Exam 70-536 Microsft .Net Framework Application Dev Foundation, and one of the problems is to create two classes, one generic, one object type that both perform the same thing; in which a loop uses the class and iterated over thousand times. And using the timer, time the performance of both. There was another post at C# generics question that seeks the same questoion but nonone replied. Basically if in my code I run the generic class first it takes loger to process. If I run the object class first than the object class takes longer to process. The whole idea was to prove that generics perform faster. I used the original users code to save me some time. I didn't particularly see anything wrong with the code and was puzzled by the outcome. Can some one explain why the unusual results? Thanks, Risho Here is the code: class Program { class Object_Sample { public Object_Sample() { Console.WriteLine("Object_Sample Class"); } public long getTicks() { return DateTime.Now.Ticks; } public void display(Object a) { Console.WriteLine("{0}", a); } } class Generics_Samle<T> { public Generics_Samle() { Console.WriteLine("Generics_Sample Class"); } public long getTicks() { return DateTime.Now.Ticks; } public void display(T a) { Console.WriteLine("{0}", a); } } static void Main(string[] args) { long ticks_initial, ticks_final, diff_generics, diff_object; Object_Sample OS = new Object_Sample(); Generics_Samle<int> GS = new Generics_Samle<int>(); //Generic Sample ticks_initial = 0; ticks_final = 0; ticks_initial = GS.getTicks(); for (int i = 0; i < 50000; i++) { GS.display(i); } ticks_final = GS.getTicks(); diff_generics = ticks_final - ticks_initial; //Object Sample ticks_initial = 0; ticks_final = 0; ticks_initial = OS.getTicks(); for (int j = 0; j < 50000; j++) { OS.display(j); } ticks_final = OS.getTicks(); diff_object = ticks_final - ticks_initial; Console.WriteLine("\nPerformance of Generics {0}", diff_generics); Console.WriteLine("Performance of Object {0}", diff_object); Console.ReadKey(); } }

    Read the article

  • Does C# 4's covariance support nesting of generics?

    - by Scott Bilas
    I don't understand why 'x' below converts, but 'y' and 'z' do not. var list = new List<List<int>>(); IEnumerable<List<int>> x = list; List<IEnumerable<int>> y = list; IEnumerable<IEnumerable<int>> z = list; Does the new covariance feature simply not work on generics of generics or am I doing something wrong? (I'd like to avoid using .Cast< to make y and z work.)

    Read the article

  • C++/CLI value class constraint won't compile. Why?

    - by Simon
    Hello, a few weeks ago a co-worker of mine spent about two hours finding out why this piece of C++/CLI code won't compile with Visual Studio 2008 (I just tested it with Visual Studio 2010... same story). public ref class Test { generic<class T> where T : value class void MyMethod(Nullable<T> nullable) { } }; The compiler says: Error 1 error C3214: 'T' : invalid type argument for generic parameter 'T' of generic 'System::Nullable', does not meet constraint 'System::ValueType ^' C:\Users\Simon\Desktop\Projektdokumentation\GridLayoutPanel\Generics\Generics.cpp 11 1 Generics Adding ValueType will make the code compile. public ref class Test { generic<class T> where T : value class, ValueType void MyMethod(Nullable<T> nullable) { } }; My question is now. Why? What is the difference between value class and ValueType?

    Read the article

  • Using generics to make an algorithm work on lists of "something" instead of only String's

    - by Binary255
    Hi, I have a small algorithm which replaces the position of characters in a String: class Program { static void Main(string[] args) { String pairSwitchedStr = pairSwitch("some short sentence"); Console.WriteLine(pairSwitchedStr); Console.ReadKey(); } private static String pairSwitch(String str) { StringBuilder pairSwitchedStringBuilder = new StringBuilder(); for (int position = 0; position + 1 < str.Length; position += 2) { pairSwitchedStringBuilder.Append((char)str[position + 1]); pairSwitchedStringBuilder.Append((char)str[position]); } return pairSwitchedStringBuilder.ToString(); } } I would like to make it as generic as possible, possibly using Generics. What I'd like to have is something which works with: Anything that is built up using a list of instances. Including strings, arrays, linked lists I suspect that the solution must use generics as the algorithm is working on a list of instances of T (there T is ... something). Version of C# isn't of interest, I guess the solution will be nicer if features from C# version 2.0 is used.

    Read the article

  • Why doesn't Java allow for the creaton of generic arrays?

    - by byte
    There are plenty of questions on stackoverflow from people who have attempted to create an array of generics like so: ArrayList<Foo>[] poo = new ArrayList<Foo>[5]; And the answer of course is that the Java specification doesn't allow you to declare an array of generics. My question however is why ? What is the technical reason underlying this restriction in the java language or java vm? It's a technical curiosity I've always wondered about.

    Read the article

  • Generic usercontrol possible?

    - by Sam
    Since .Net 4 does support generics in XAML, I'd like to create a UserControl using generics, like: public class MyComboBox<T> { } I can declare the UserControl quite well, but how would I use it in a XAML file? Or can't this be done in XAML?

    Read the article

  • Injecting generics with Guice

    - by paradigmatic
    I am trying to migrate a small project, replacing some factories with Guice (it is my first Guice trial). However, I am stuck when trying to inject generics. I managed to extract a small toy example with two classes and a module: import com.google.inject.Inject; public class Console<T> { private final StringOutput<T> out; @Inject public Console(StringOutput<T> out) { this.out = out; } public void print(T t) { System.out.println(out.converter(t)); } } public class StringOutput<T> { public String converter(T t) { return t.toString(); } } import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.TypeLiteral; public class MyModule extends AbstractModule { @Override protected void configure() { bind(StringOutput.class); bind(Console.class); } public static void main(String[] args) { Injector injector = Guice.createInjector( new MyModule() ); StringOutput<Integer> out = injector.getInstance(StringOutput.class); System.out.println( out.converter(12) ); Console<Double> cons = injector.getInstance(Console.class); cons.print(123.0); } } When I run this example, all I got is: Exception in thread "main" com.google.inject.CreationException: Guice creation errors: 1) playground.StringOutput<T> cannot be used as a key; It is not fully specified. at playground.MyModule.configure(MyModule.java:15) 1 error at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:354) at com.google.inject.InjectorBuilder.initializeStatically(InjectorBuilder.java:152) at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:105) at com.google.inject.Guice.createInjector(Guice.java:92) I tried looking for the error message, but without finding any useful hints. Further on the Guice FAQ I stumble upon a question about how to inject generics. I tried to add the following binding in the configure method: bind(new TypeLiteral<StringOutput<Double>>() {}).toInstance(new StringOutput<Double>()); But without success (same error message). Can someone explain me the error message and provide me some tips ? Thanks.

    Read the article

  • C# Generics - Strange Interview Question

    - by udana
    An interviewer argued me "Genrics are not completely Genrics", He provided the example (Parameters int k,int d are not generic) public static void PrintThis<T>(T a, T b, T c, int k,int d) { } He asked me if i prove still it is generics , i will be allowed to take up the next round. I did not know what he is expecting from me,and what he really means by showing such example. Guide me how to smartly face such a strange interview ?. Thanks in advance.

    Read the article

  • Using custom DataContractResolver in WCF, to transport inheritance trees involving generics

    - by Benson
    I've got a WCF service, in which there are operations which accept a non-generic base class as parameter. [DataContract] class Foo { ... } This base class is in turn inherited, by such generics classes as [DataContract] class Bar : Foo { ... } To get this to work, I'd previously have to register KnownTypes for the Foo class, and have these include all possible variations of Bar (such as Bar, Bar and even Bar). With the DataContractResolver in .NET 4, however, I should be able to build a resolver which properly stores (and restores) the classes. My questions: Are DataContractResolvers typically only used on the service side, and not by the client? If so, how would that be useful in this scenario? Am I wrong to write a DataContractResolver which serializes the fully qualified type name of a generic type, such as Bar1[List1[string, mscorlib], mscorlib] ? Couldn't the same DataContractResolver on the client side restore these types?

    Read the article

  • Signature of Collections.min/max method

    - by Marco
    In Java, the Collections class contains the following method: public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> c) Its signature is well-known for its advanced use of generics, so much that it is mentioned in the Java in a Nutshell book and in the official Sun Generics Tutorial. However, I could not find a convincing answer to the following question: Why is the formal parameter of type Collection<? extends T>, rather than Collection<T>? What's the added benefit?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >