Search Results

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

Page 29/41 | < Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >

  • Is it possible to write a generic +1 method for numeric box types in Java?

    - by polygenelubricants
    This is NOT homework. Part 1 Is it possible to write a generic method, something like this: <T extends Number> T plusOne(T num) { return num + 1; // DOESN'T COMPILE! How to fix??? } Short of using a bunch of instanceof and casts, is this possible? Part 2 The following 3 methods compile: Integer plusOne(Integer num) { return num + 1; } Double plusOne(Double num) { return num + 1; } Long plusOne(Long num) { return num + 1; } Is it possible to write a generic version that bound T to only Integer, Double, or Long?

    Read the article

  • Why can't I enforce derived classes to have parameterless constructors?

    - by FrisbeeBen
    I am trying to do the following: public class foo<T> where T : bar, new() { public foo() { _t = new T(); } private T _t; } public abstract class bar { public abstract void someMethod(); // Some implementation } public class baz : bar { public overide someMethod(){//Implementation} } And I am attempting to use it as follows: foo<baz> fooObject = new foo<baz>(); And I get an error explaining that 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. I fully understand why this must be, and also understand that I could pass a pre-initialized object of type 'T' in as a constructor argument to avoid having to 'new' it, but is there any way around this? any way to enforce classes that derive from 'bar' to supply parameterless constructors?

    Read the article

  • Generic delegate instances

    - by Luc C
    I wonder if C# (or the underlying .NET framework) supports some kind of "generic delegate instances": that is a delegate instance that still has an unresolved type parameter, to be resolved at the time the delegate is invoked (not at the time the delegate is created). I suspect this isn't possible, but I'm asking it anyway... Here is an example of what I'd like to do, with some "???" inserted in places where the C# syntax seems to be unavailable for what I want. (Obviously this code doesn't compile) class Foo { public T Factory<T>(string name) { // implementation omitted } } class Test { public void TestMethod() { Foo foo = new Foo(); ??? magic = foo.Factory; // No type argument given here yet to Factory! // What would the '???' be here (other than 'var' :) )? string aString = magic<string>("name 1"); // type provided on call int anInt = magic<int>("name 2"); // another type provided on another call // Note the underlying calls work perfectly fine, these work, but i'd like to expose // the generic method as a delegate. string aString2 = foo.Factory<string>("name 1"); int anInt2 = foo.Factory<int>("name 2"); } } Is there a way to actually do something like this in C#? If not, is that a limitation in the language, or is it in the .NET framework?

    Read the article

  • How to convert string to any type

    - by DJPB
    Hi there I want to convert a string to a generic type I have this: string inputValue = myTxtBox.Text; PropertyInfo propInfo = typeof(MyClass).GetProperty(myPropertyName); Type propType = propInfo.PropertyType; object propValue = ????? I want to convert 'inputString' to the type of that property, to check if it's compatible how can I do that? tks

    Read the article

  • How to use method hiding (new) with generic constrained class

    - by ongle
    I have a container class that has a generic parameter which is constrained to some base class. The type supplied to the generic is a sub of the base class constraint. The sub class uses method hiding (new) to change the behavior of a method from the base class (no, I can't make it virtual as it is not my code). My problem is that the 'new' methods do not get called, the compiler seems to consider the supplied type to be the base class, not the sub, as if I had upcast it to the base. Clearly I am misunderstanding something fundamental here. I thought that the generic where T: xxx was a constraint, not an upcast type. This sample code basically demonstrates what I'm talking about. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericPartialTest { class ContextBase { public string GetValue() { return "I am Context Base: " + this.GetType().Name; } public string GetOtherValue() { return "I am Context Base: " + this.GetType().Name; } } partial class ContextSub : ContextBase { public new string GetValue() { return "I am Context Sub: " + this.GetType().Name; } } partial class ContextSub { public new string GetOtherValue() { return "I am Context Sub: " + this.GetType().Name; } } class Container<T> where T: ContextBase, new() { private T _context = new T(); public string GetValue() { return this._context.GetValue(); } public string GetOtherValue() { return this._context.GetOtherValue(); } } class Program { static void Main(string[] args) { Console.WriteLine("Simple"); ContextBase myBase = new ContextBase(); ContextSub mySub = new ContextSub(); Console.WriteLine(myBase.GetValue()); Console.WriteLine(myBase.GetOtherValue()); Console.WriteLine(mySub.GetValue()); Console.WriteLine(mySub.GetOtherValue()); Console.WriteLine("Generic Container"); Container<ContextBase> myContainerBase = new Container<ContextBase>(); Container<ContextSub> myContainerSub = new Container<ContextSub>(); Console.WriteLine(myContainerBase.GetValue()); Console.WriteLine(myContainerBase.GetOtherValue()); Console.WriteLine(myContainerSub.GetValue()); Console.WriteLine(myContainerSub.GetOtherValue()); Console.ReadKey(); } } }

    Read the article

  • Comparing the values of two generic Numbers

    - by PartlyCloudy
    I want to compare to variables, both of type T extends Number. Now I want to know which of the two variables is greater than the other or equal. Unfortunately I don't know the exact type yet, I only know that it will be a subtype of java.lang.Number. How can I do that? Thanks!

    Read the article

  • unable to pas derived List<>

    - by Tarscher
    Hi all, I have class A {} class B : A {} I also have a method that expects a List parameter void AMethod(List<A> parameter) {} Why can't I List<B> bs = new List<B>(); AMethod(bs); And secondly what is the most elegant way to make this work? regards

    Read the article

  • When using a repository is it possible for a type to return a Func that the repository uses to test for existing entities?

    - by Scott Rickman
    For example given a Factory with a method public static T Save<T>(T item) where T : Base, new() { /* item.Id == Guid.Empty therefore item is new */ if (item.Id == Guid.Empty && repository.GetAll<T>(t => t.Name == item.Name)) { throw new Exception("Name is not unique"); } } how do I create a property of Base (say MustNotAlreadyExist) so that I can change the method above to public static T Save<T>(T item) where T : Base, new() { /* item.Id == Guid.Empty therefore item is new */ if (item.Id == Guid.Empty && repository.GetAll<T>(t.MustNotAlreadyExist)) { throw new Exception("Name is not unique"); } } public class Base { ... public virtual Expression<Func<T, bool>> MustNotAlreadyExist() { return (b => b.Name == name); /* <- this clearly doesn't work */ } } and then how can I override MustNotAlreadyExist in Account : Base public class Account : Base { ... public override Expression<Func<T, bool>> MustNotAlreadyExist() { return (b => b.Name == name && b.AccountCode == accountCode); /* <- this doesn't work */ } ... }

    Read the article

  • Overriding inherited generic methods

    - by jess
    I have this code in base class protected virtual bool HasAnyStuff<TObject>(TObject obj) where TObject:class { return false; } In child class I am overriding protected override bool HasAnyStuff<Customer>(Customer obj) { //some stuff if Customer.sth etc return false; } I am getting this error '''Type parameter declaration must be an identifier not a type''' What is it I am doing wrong here?

    Read the article

  • Why isn't the new() generic constraint satisfied by a class with optional parameters in the construc

    - by Joshua Flanagan
    The following code fails to compile, producing a "Widget must be a non-abstract type with a public parameterless constructor" error. I would think that the compiler has all of the information it needs. Is this a bug? An oversight? Or is there some scenario where this would not be valid? public class Factory<T> where T : new() { public T Build() { return new T(); } } public class Widget { public Widget(string name = "foo") { Name = name; } public string Name { get; set; } } public class Program { public static void Main() { var widget = new Widget(); // this is valid var factory = new Factory<Widget>(); // compiler error } }

    Read the article

  • A strange error in java generic.

    - by ???
    This is ok: Class<? extends String> stringClass = "a".getClass(); But this gets error: <T> void f(T obj) { Class<? extends T> objClass = obj.getClass(); } I know I can cast it like: <T> void f(T obj) { @SuppressWarnings("unchecked") Class<? extends T> objClass = (Class<? extends T>) obj.getClass(); } But why the previous error? Will the next release of Java 7 will support such usage?

    Read the article

  • Catch a generic exception in Java?

    - by Alex Baranosky
    We use JUnit 3 at work and there is no ExpectedException annotation. I wanted to add a utility to our code to wrap this: try { someCode(); fail("some error message"); } catch (SomeSpecificExceptionType ex) { } So I tried this: public static class ExpectedExceptionUtility { public static <T extends Exception> void checkForExpectedException(String message, ExpectedExceptionBlock<T> block) { try { block.exceptionThrowingCode(); fail(message); } catch (T ex) { } } } However, Java cannot use generic exception types in a catch block, I think. How can I do something like this, working around the Java limitation? Is there a way to check that the ex variable is of type T?

    Read the article

  • scala 2.8 CanBuildFrom

    - by oxbow_lakes
    Following on from another question I asked, I wanted to understand a bit more about the Scala method TraversableLike[A].map whose signature is as follows: def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That Notice a few things about this method: it takes a function turning each A in the traversable into a B it returns That and takes an implicit argument of type CanBuildFrom[Repr, B, That] I can call this as follows: > val s: Set[Int] = List("Paris", "London").map(_.length) s: Set[Int] Set(5,6) What I cannot quite grasp is how the fact that That is bound to B (i.e. it is some collection of B's) is being enforced by the compiler. The type parameters look to be independent in both the signature above and in the signature of the trait CanBuildFrom itself: trait CanBuildFrom[-From, -Elem, +To] How is the scala compiler ensuring that That cannot be forced into something which does not make sense? > val s: Set[String] = List("Paris", "London").map(_.length) //will not compile EDIT - this question of course boils down to: How does the compiler decide what implicit CanBuildFrom objects are in scope for the call?

    Read the article

  • Why does this static factory method involving implied generic types, work?

    - by Cheeso
    Consider public class Tuple<T1, T2> { public Tuple(T1 v1, T2 v2) { V1 = v1; V2 = v2; } public T1 V1 { get; set; } public T2 V2 { get; set; } } public static class Tuple { // MAGIC!! public static Tuple<T1, T2> New<T1, T2>(T1 v1, T2 v2) { return new Tuple<T1, T2>(v1, v2); } } Why does the part labeled "MAGIC" in the above work? It allows syntax like Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2"), but ... how and why? Why do I not need Tuple.New<int,string>(1, "2") ??

    Read the article

  • Why can't these generic type parameters be inferred?

    - by Jon M
    Given the following interfaces/classes: public interface IRequest<TResponse> { } public interface IHandler<TRequest, TResponse> where TRequest : IRequest<TResponse> { TResponse Handle(TRequest request); } public class HandlingService { public TResponse Handle<TRequest, TResponse>(TRequest request) where TRequest : IRequest<TResponse> { var handler = container.GetInstance<IHandler<TRequest, TResponse>>(); return handler.Handle(request); } } public class CustomerResponse { public Customer Customer { get; set; } } public class GetCustomerByIdRequest : IRequest<CustomerResponse> { public int CustomerId { get; set; } } Why can't the compiler infer the correct types, if I try and write something like the following: var service = new HandlingService(); var request = new GetCustomerByIdRequest { CustomerId = 1234 }; var response = service.Handle(request); // Shouldn't this know that response is going to be CustomerResponse? I just get the 'type arguments cannot be inferred' message. Is this a limitation with generic type inference in general, or is there a way to make this work?

    Read the article

  • How can I define a constructor in an open generic type?

    - by Cort
    I am trying to create on open generic type that has a constructor to be used by derived types, but I either don't know how to do it or it is not possible -- not sure which. public struct DataType<T> : IDataType { private T myValue; private TypeState myState; private DataType<T>(T initialValue, TypeState state) { myValue = initialValue; myState = state; } } Any help much appreciated! Cort

    Read the article

  • What's the most efficient way to combine two List(Of String)?

    - by Jason Towne
    Let's say I've got: Dim los1 as New List(Of String) los1.Add("Some value") Dim los2 as New List(Of String) los2.Add("More values") What would be the most efficient way to combine the two into a single List(Of String)? Edit: While I'm loving the solutions everyone has provided so far, I probably should also mention I'm stuck using the .NET 2.0 framework. Any other suggestions?

    Read the article

  • is this possible: c# collection of Type with constrains, or collection of generic type?

    - by Jon
    I'm trying to store types in a collection, so that i can later instantiate objects of the types in the collection. But I'm not sure how to do this the best way. What i have so far: List<Type> list = new List<Type>(); list.Add(typeof(MyClass)); var obj = (MyClass)Activator.CreateInstance(list[0]); I would like to have some constrains on the Type, or better yet, just a generic type in the collection instead of an instantiated Type object. Is this possible?

    Read the article

  • Html.Editor() helper in ASP.NET MVC 3 does not work as expected with array in model

    - by SlimShaggy
    In my ASP.NET MVC 3 application I have classes like the following: public class Localization<T> { public int VersionID { get; set; } public T Value { get; set; } ... } public class Localizable<T> { public Localization<T>[] Name { get; set; } ... } Then, I have the following view: @model dynamic ... @for (int i = 0; i < VersionCount; i++) { ... @Html.Editor(string.Format("Name[{0}.Value", i)) ... } Now, when I display this view, passing a subclass of Localizable<string> as the model, the textboxes for the strings are rendered, but they are empty. If I replace @Html.Editor(string.Format("Name[{0}.Value", i)) with @InputExtensions.TextBox(Html, string.Format("Name[{0}].Value", i), Model.Name[i].Value), the textboxes are correctly filled with values from the model. However, using TextBox instead of Editor is not an option for me, because I want to use different editor templates for different types of T. So, what am I doing wrong, or is it a bug in MVC, and is there any workaround?

    Read the article

  • C# determining generic type

    - by Chris Klepeis
    I have several templated objects that all implement the same interface: I.E. MyObject<datatype1> obj1; MyObject<datatype2> obj2; MyObject<datatype3> obj3; I want to store these objects in a List... I think I would do that like this: private List<MyObject<object>> _myList; I then want to create a function that takes 1 parameter, being a datatype, to see if an object using that datatype exists in my list.... sorta clueless how to go about this. In Pseudo code it would be: public bool Exist(DataType T) { return (does _myList contain a MyObject<T>?); }

    Read the article

  • How to convet DataTable to List on runtype with out existin class property [closed]

    - by shamim
    Work on VS2010 C#,Have one DataTable ,want to convert this DataTable to List Suppose: Table dt; On run time want to create similar field from a datatable and fill fields in List.There is no existing class for list properties. ListName=TableName List property name=Table column name List Property type=Table column type List items=Table rows Note: Recently work on EF.To fullfill my project requirement, need to give flexibility to use to input and execute ESQL at runtime .I don’t want to put this execute result on datatable or List ,want to put this result on list. List has no existing class and property,don’t want to convert DataTable on list Type:DataRow If have any query please ask,Thanks in advanced.

    Read the article

  • Generic collection class?

    - by Mark
    Is there anyway I can do this? class TSOC<TCollection, TValue> : ICollection<TValue>, INotifyCollectionChanged where TCollection : ICollection { private TCollection<TValue> collection; } It doesn't like my definition of collection. I'd prefer the definition to look like TSOC<TCollection> where the user can pass in List<int> or something, but then I need to pull out the "int" to know what interface to implement.

    Read the article

  • Common type for generic classes of different types

    - by DinGODzilla
    I have (for example) Dictionary of different generic types (d1, d2, d3, d4) and I want to store them in something var d1 = new Dictionary<int, string>(); var d2 = new Dictionary<int, long>(); var d3 = new Dictionary<DateTime, bool>(); var d4 = new Dictionary<string, object>(); var something = ??? //new List<object> {d1, d2, d3, d4}; Is there any other way how to store that in something with common denominator different than object? Thanks :-)

    Read the article

  • How to get all possible generic type in StructureMap?

    - by Soul_Master
    I just used StructureMap few days ago. I use StructureMap for collecting all validator class like the following code. public class BaseClassA {} public class ClassB : BaseClassA {} public class ClassC : BaseClassB {} public BaseClassAValidator : IValidator<BaseClassA>() {} In StructureMap, I only register IValidator interface for BaseClassAValidator class. But I want to get the same result when I call IValidator or IValidator that mean StructureMap should return IValidator where T is requested class or parent class of requested class. Is it possible? Or I need to manually call it.

    Read the article

< Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >