Search Results

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

Page 14/41 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Calling a generic function in VB.NET / C#

    - by Quandary
    Question: I want to call a generic function, defined as: Public Shared Function DeserializeFromXML(Of T)(Optional ByRef strFileNameAndPath As String = Nothing) As T Now when I call it, I wanted to do it with any of the variants below: Dim x As New XMLserialization.cConfiguration x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of x)() x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(GetType(x))() x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of GetType(x))() But it doesn't work. I find it very annoying and unreadable having to type x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of XMLserialization.cConfiguration)() Is there a way to call a generic function by getting the type from the instance ?

    Read the article

  • Variadic templates in Scala

    - by Thomas Jung
    Suppose you want to have something like variadic templates (the ability to define n type parameters for a generic class) in Scala. For example you do not want to define Tuple2[+T1, +T2] and Tuple3[+T1, +T2, +T3] but Tuple[T*]. Are there other options than HLists?

    Read the article

  • C# Generic Static Constructor

    - by Seattle Leonard
    Will a static constructor on a generic class be run for every type you pass into the generic parameter such as this: class SomeGenericClass<T> { static List<T> _someList; static SomeGenericClass() { _someList = new List<T>(); } } Are there any draw backs to using this approach?

    Read the article

  • Calling a static method on a generic type parameter

    - by Remi Despres-Smyth
    I was hoping to do something like this, but it appears to be illegal in C#: public Collection MethodThatFetchesSomething<T>() where T : SomeBaseClass { return T.StaticMethodOnSomeBaseClassThatReturnsCollection(); } I get a compile-time error: "'T' is a 'type parameter', which is not valid in the given context." Given a generic type parameter, how can I call a static method on the generic class? The static method has to be available, given the constraint.

    Read the article

  • C# Anonymous method variable scope problem with IEnumerable<T>

    - by PaN1C_Showt1Me
    Hi. I'm trying to iterate through all components and for those who implements ISupportsOpen allow to open a project. The problem is when the anonymous method is called, then the component variable is always the same element (as coming from the outer scope from IEnumerable) foreach (ISupportsOpen component in something.Site.Container.Components.OfType<ISupportsOpen>()) { MyClass m = new MyClass(); m.Called += new EventHandler(delegate(object sender, EventArgs e) { if (component.CanOpenProject(..)) component.OpenProject(..); }); itemsList.Add(m); } How should it be solved, please?

    Read the article

  • Generic structure for performing string conversion when data binding.

    - by Rohan West
    Hi there, a little while ago i was reading an article about a series of class that were created that handled the conversion of strings into a generic type. Below is a mock class structure. Basically if you set the StringValue it will perform some conversion into type T public class MyClass<T> { public string StringValue {get;set;} public T Value {get;set;} } I cannot remember the article that i was reading, or the name of the class i was reading about. Is this already implemented in the framework? Or shall i create my own?

    Read the article

  • Using string[] as a Dictionary key e.g. Dictionary<string[], StringBuilder>

    - by Nick Allen - Tungle139
    The structure I am trying to achieve is a composite Dictionary key which is item name and item displayname and the Dictionary value being the combination of n strings So I came up with var pages = new Dictionary<string[], StringBuilder>() { { new string[] { "food-and-drink", "Food & Drink" }, new StringBuilder() }, { new string[] { "activities-and-entertainment", "Activities & Entertainment" }, new StringBuilder() } }; foreach (var obj in my collection) { switch (obj.Page) { case "Food": case "Drink": pages["KEY"].Append("obj.PageValue"); break; ... } } The part I am having trouble with is accessing the Dictionary Key pages["KEY"] How do I target the Dictionary Key whose value at [0] == some value? Hope that makes sense

    Read the article

  • CSharp: Testing a Generic Class

    - by Jonas Gorauskas
    More than a question, per se, this is an attempt to compare notes with other people. I wrote a generic History class that emulates the functionality of a browser's history. I am trying to wrap my head around how far to go when writing unit tests for it. I am using NUnit. Please share your testing approaches below. The full code for the History class is here (http://pastebin.com/ZGKK2V84).

    Read the article

  • 'Set = new HashSet' or 'HashSet = new Hashset'?

    - by Pureferret
    I'm intialising a HashSet like so in my program: Set<String> namesFilter = new HashSet<String>(); Is this functionally any different if I initilise like so? HashSet<String> namesFilter = new HashSet<String>(); I've read this about the collections interface, and I understand interfaces (well, except their use here). I've read this excerpt from Effective Java, and I've read this SO question, but I feel none the wiser. Is there a best practice in Java, and if so, why? My intuition is that it makes casting to a different type of Set easier in my first example. But then again, you'd only be casting to something that was a collection, and you could convert it by re-constructing it.

    Read the article

  • Can't operator == be applied to generic types in C#?

    - by Hosam Aly
    According to the documentation of the == operator in MSDN, For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types. So why does this code snippet fail to compile? void Compare<T>(T x, T y) { return x == y; } I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the == operator is predefined for all types? Edit: Thanks everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is not correct. But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one? Edit 2: Through trial and error, we learned that the == operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true, even when Test.test<B>(new B(), new B()) is called: class A { public static bool operator==(A x, A y) { return true; } } class B : A { public static bool operator==(B x, B y) { return false; } } class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }

    Read the article

  • Combining List<>'s in .NET

    - by Maxim Z.
    I have a few List< objects that hold many objects of one specific type. My goal is to combine these List<'s into one List<. Of course, I could just loop through each List's contents and add them into one final List, but is there a more efficient way?

    Read the article

  • Create Generic method constraining T to an Enum

    - by johnc
    I'm building a function to extend the Enum.Parse concept that allows a default value to be parsed in case that an Enum value is not found Is case insensitive So I wrote the following public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } I am getting a Error Constraint cannot be special class 'System.Enum' Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks Have settled on (I've left the loop to maintain case insensitivity - I am usng this when parsing XML) public static class EnumUtils { public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type"); if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } }

    Read the article

  • Covariance and Contravariance type inference in C# 4.0

    - by devoured elysium
    When we define our interfaces in C# 4.0, we are allowed to mark each of the generic parameters as in or out. If we try to set a generic parameter as out and that'd lead to a problem, the compiler raises an error, not allowing us to do that. Question: If the compiler has ways of inferring what are valid uses for both covariance (out) and contravariance(in), why do we have to mark interfaces as such? Wouldn't it be enough to just let us define the interfaces as we always did, and when we tried to use them in our client code, raise an error if we tried to use them in an un-safe way? Example: interface MyInterface<out T> { T abracadabra(); } //works OK interface MyInterface2<in T> { T abracadabra(); } //compiler raises an error. //This makes me think that the compiler is cappable //of understanding what situations might generate //run-time problems and then prohibits them. Also, isn't it what Java does in the same situation? From what I recall, you just do something like IMyInterface<? extends whatever> myInterface; //covariance IMyInterface<? super whatever> myInterface2; //contravariance Or am I mixing things? Thanks

    Read the article

  • calling Overloaded method from a generic method.

    - by asela38
    How to create a generic method which can call overloaded methods? I tried but it gives a compilation error. Test.java:19: incompatible types found : java.lang.Object required: T T newt = getCloneOf(t); ^ import java.util.*; public class Test { private Object getCloneOf(Object s) { return new Object(); } private String getCloneOf(String s) { return new String(s); } private <T> Set<T> getCloneOf(Set<T> set){ Set<T> newSet = null; if( null != set) { newSet = new HashSet<T>(); for (T t : set) { T newt = getCloneOf(t); newSet.add(newt); } } } }

    Read the article

  • C# cast Foo<Bar> to Foo<object>

    - by Michael
    Hi, does anyone know if it is possible to cast a generic type with a certain type parameter (e.g. Bar) to the same generic type with the type parameter being a base type of Bar (such as object in my case). And, if it is possible, how would it be done? What I want to do is have a collection of Foo but be able to add Foos with more specific type arguments. Thanks

    Read the article

  • C# to Java: where T : new() Syntax

    - by Shiftbit
    I am porting some C# code over to Java. I am having trouble with the where Syntax, specifically new(). I understand that where is similar to Java's generic: T extends FOO. How I can replicate the new() argument in Java? "The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless--or default-- constructor." - MSDN ie: public class BAR<T> : BAR where T : FOO, new() Right now I have: public class BAR<T extends FOO> extends ABSTRACTBAR { public HXIT(T t){ this.value = t; } .... }

    Read the article

  • Casting a non-generic type to a generic one

    - by John Sheehan
    I've got this class: class Foo { public string Name { get; set; } } And this class class Foo<T> : Foo { public T Data { get; set; } } Here's what I want to do: public Foo<T> GetSome() { Foo foo = GetFoo(); Foo<T> foot = (Foo<T>)foo; foot.Data = GetData<T>(); return foot; } What's the easiest way to convert Foo to Foo<T>? I can't cast directly InvalidCastException) and I don't want to copy each property manually (in my actual use case, there's more than one property) if I don't have to. Is a user-defined type conversion the way to go?

    Read the article

  • Holding value in collection

    - by Amit Ranjan
    I have a application which is on timesheet. I have total of 54 columns out of which 10 columns are visible rest invisible. First 3 columns are Project, MileStone and Classes. Rest are Sun- Sat work hrs. Now I have a column named 'taskid' as SunTaskID,MonTaskID and so on till SatTaskID for holding each days taskid. Now on the selection of SunHrs (Sunday's Work Hrs), i retrieve that days taskid and on the basis of task id i retrieve attachments which is displayed under a listbox. Now the problem is that since a day can have multiple attachments and a user can attach multiple attachments at time. He can enter values from grid to. Grid cells are editable. I am using BindingList(of TaskClass) in VB.Net for binding grid. I have total 54 properties n my task class. So i want to what property do i need to hod each days attachment and in what way. Earlier I tried Dictionary. But i was not aware of its usage as a property so i gave. Then prepared a separate class for attachment but, it was difficult to synchronize the existing attachments with taskid...

    Read the article

  • java.lang.Void in C#?

    - by user313661
    Hi, I am currently working with .Net 2.0 and have an interface whose generic type is used to define a method's return type. Something like interface IExecutor<T> { T Execute() { ... } } My problem is that some classes that implement this interface do not really need to return anything. In Java you can use java.lang.Void for this purpose, but after quite a bit of searching I found no equivalent in C#. More generically, I also did not find a good way around this problem. I tried to find how people would do this with delegates, but found nothing either - which makes me believe that the problem is that I suck at searching :) So what's the best way to solve this? How would you do it? Thanks!

    Read the article

  • How can I improve this design?

    - by klausbyskov
    Let's assume that our system can perform actions, and that an action requires some parameters to do its work. I have defined the following base class for all actions (simplified for your reading pleasure): public abstract class BaseBusinessAction<TActionParameters> : where TActionParameters : IActionParameters { protected BaseBusinessAction(TActionParameters actionParameters) { if (actionParameters == null) throw new ArgumentNullException("actionParameters"); this.Parameters = actionParameters; if (!ParametersAreValid()) throw new ArgumentException("Valid parameters must be supplied", "actionParameters"); } protected TActionParameters Parameters { get; private set; } protected abstract bool ParametersAreValid(); public void CommonMethod() { ... } } Only a concrete implementation of BaseBusinessAction knows how to validate that the parameters passed to it are valid, and therefore the ParametersAreValid is an abstract function. However, I want the base class constructor to enforce that the parameters passed are always valid, so I've added a call to ParametersAreValid to the constructor and I throw an exception when the function returns false. So far so good, right? Well, no. Code analysis is telling me to "not call overridable methods in constructors" which actually makes a lot of sense because when the base class's constructor is called the child class's constructor has not yet been called, and therefore the ParametersAreValid method may not have access to some critical member variable that the child class's constructor would set. So the question is this: How do I improve this design? Do I add a Func<bool, TActionParameters> parameter to the base class constructor? If I did: public class MyAction<MyParameters> { public MyAction(MyParameters actionParameters, bool something) : base(actionParameters, ValidateIt) { this.something = something; } private bool something; public static bool ValidateIt() { return something; } } This would work because ValidateIt is static, but I don't know... Is there a better way? Comments are very welcome.

    Read the article

  • Is this a good way to expose generic base class methods through an interface?

    - by Nate Heinrich
    I am trying to provide an interface to an abstract generic base class. I want to have a method exposed on the interface that consumes the generic type, but whose implementation is ultimately handled by the classes that inherit from my abstract generic base. However I don't want the subclasses to have to downcast to work with the generic type (as they already know what the type should be). Here is a simple version of the only way I can see to get it to work at the moment. public interface IFoo { void Process(Bar_base bar); } public abstract class FooBase<T> : IFoo where T : Bar_base { abstract void Process(T bar); // Explicit IFoo Implementation void IFoo.Process(Bar_base bar) { if (bar == null) throw new ArgumentNullException(); // Downcast here in base class (less for subclasses to worry about) T downcasted_bar = bar as T; if (downcasted_bar == null) { throw new InvalidOperationException( string.Format("Expected type '{0}', not type '{1}'", T.ToString(), bar.GetType().ToString()); } //Process downcasted object. Process(downcasted_bar); } } Then subclasses of FooBase would look like this... public class Foo_impl1 : FooBase<Bar_impl1> { void override Process(Bar_impl1 bar) { //No need to downcast here! } } Obviously this won't provide me compile time Type Checking, but I think it will get the job done... Questions: 1. Will this function as I think it will? 2. Is this the best way to do this? 3. What are the issues with doing it this way? 4. Can you suggest a different approach? Thanks!

    Read the article

  • Is generic Money<TAmount> a good implementation idea?

    - by jdk
    I have a Money Type that allows math operations and is sensitive to exchange rates so it will reduce one currency to another if rate is available to calculate in a given currency, rounds by various methods. It has other features that are sensitive to money, but I need to ask if the basic data type used should be made generic in nature. I've realized that the basic data type to hold an amount may differ for financial situations, for example: retail money might be expressed as all cents using int or long where fractions of cents do not matter, decimal is commonly used for its fixed behaviour, sometimes double seems to be used for big finance and large values sometimes a special BigInteger or 3rd-party type is used. I want to know if it would be considered good form to turn Money into Money<T_amount> so it can be used in any one of the above chosen scenarios?

    Read the article

  • Testing a Generic Class

    - by Jonas Gorauskas
    More than a question, per se, this is an attempt to compare notes with other people. I wrote a generic History class that emulates the functionality of a browser's history. I am trying to wrap my head around how far to go when writing unit tests for it. I am using NUnit. Please share your testing approaches below. The full code for the History class is here (http://pastebin.com/ZGKK2V84).

    Read the article

  • Castle Windsor - Resolving a generic implementation to a base type

    - by arootbeer
    I'm trying to use Windsor as a factory to provide specification implementations based on subtypes of XAbstractBase (an abstract message base class in my case). I have code like the following: public abstract class XAbstractBase { } public class YImplementation : XAbstractBase { } public class ZImplementation : XAbstractBase { } public interface ISpecification<T> where T : XAbstractBase { bool PredicateLogic(); } public class DefaultSpecificationImplementation : ISpecification<XAbstractBase> { public bool PredicateLogic() { return true; } } public class SpecificSpecificationImplementation : ISpecification<YImplementation> { public bool PredicateLogic() { /*do real work*/ } } My component registration code looks like this: container.Register( AllTypes.FromAssembly(Assembly.GetExecutingAssembly()) .BasedOn(typeof(ISpecification<>)) .WithService.FirstInterface() ) This works fine when I try to resolve ISpecification<YImplementation>; it correctly resolves SpecificSpecificationImplementation. However, when I try to resolve ISpecification<ZImplementation> Windsor throws an exception: "No component for supporting the service ISpecification'1[ZImplementation, AssemblyInfo...] was found" Does Windsor support resolving generic implementations down to base classes if no more specific implementation is registered?

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >