C# - How To Return A Value Based On The Type Of The Generic T
Jun 16, 2010
I have a method like:
public T Get<T>(string key)
{
}
Now say I want to return "hello" if the type is a string, and 110011 if it is type int.
how can I do that?
typeof(T) doesn't seem to work.
I ideally want to do a switch statement, and return something based on the Type of the generic (string/int/long/etc).
View 5 Replies
Similar Messages:
Nov 25, 2010
I'm trying to create a control out of a class I found, and one of the overridden functions is the following:
protected override void PerformDataBinding(IEnumerable data)
However, when I try to build the control I'm getting the error as shown in the subject. I've tried searching, and it seems the signature for the original function matches the one I have, and all other solutions I've seen uses the same signature.
View 3 Replies
Feb 14, 2011
I want to create a function which would have two parameters
public **XYZ** GetOputput(string strToConvert, **ABC**)
What I want from this function, that I will send a string to this function and the datatype in which I want to convert this string [Ex: Int32,Int64, datetime etc..] and the return will be the same as the datatype I have sent as the input parameter.
I want to have something like this in my function:
[code]....
View 5 Replies
Mar 5, 2011
I'm trying to create a validation layer that will contain methods to validate all my objects (in my Business Objects layer) .. but when I try to reference both the validation and business objects to each other I get a circular dependency error .. so I've decided to create a new layer (BLL) to validate the objects for me and I'll be able to reference both the validation and the object layers.
so I want to build some kind of class/interface -I don't know what fits more- to be like a generic type or a parent type that my method could accept it as a parameter and check for it's Name/ID property. Instead of defining a new method overload for each object type I have
Simplification
View 1 Replies
Jan 22, 2010
Can my WebMethod return an XmlDocument as return type?
When I try to consume the web service I'm still not getting XML. It appears as though a reference to the method is being returned rather than say a string containing XML.
<WebMethod()> _
Public Function CustomerSearch(ByVal lastName As String, ByVal firstName As String, ByVal companyName As String, ByVal city As String, ByVal state As String, ByVal email As String) As XmlDocument
' Create XML doc
Dim doc As XmlDocument = New XmlDocument()
' some more code
Return doc
End Function
View 4 Replies
Nov 11, 2010
I want to write a generic function which return either string or Xdocument
[Code]....
In default.aspx
XDocument doc = api.CreateJob<XDocument>("xyz");
threws the exception "Invalid cast from 'System.String' to 'System.Xml.Linq.XDocument'."
How can i do this
View 6 Replies
Dec 10, 2010
ASP.NET 3.5 C# I am joining two tables using Linq. Table names are MapAssets and ExitPoint. In Database they are related with 'has a relationship'
I am writing a function in my BLL to return the joined table
public List<ExitPoints> GetExitPointDetailsByProjectID(int iProjectID)
{
ctx = new CoreDBDataContext();
var exitPointDetails = from ma in ctx.MapAssets
join ep in ctx.ExitPoints
on ma.MapAssetID equals ep.MapAssetID
where ma.ProjectID == iProjectID
select new
{
//would like to have data from both tables here
ctx.MapAssets,
ctx.ExitPoints
};
return exitPointDetails.ToList();
}
This obviuosly doesn't work. And I dont know what to return at all. All constraint I have for the return is to be able to be bound to a gridview. is this the correct way? Or else whats the correct way?
View 6 Replies
Oct 30, 2010
how would i go about returning a generic list in json format, can anyone point me to any good examples.
View 2 Replies
Apr 4, 2011
We have created a class to wrap the payload of web service response with common information as follows.
public class ItemResponse<T> : Response
{
/// <summary>
[code]...
View 2 Replies
Mar 25, 2011
I am trying to set property value using reflection as below. I wanted to know if there is any generic way of finding the property type instead of doing it int he below way.
string currentlblTxt;
string currentTxt;
Assembly assembly = Assembly.GetAssembly(typeof(myAdapter));
myAdapter currentEventObject = (myAdapter)assembly.CreateInstance(myClassName);
[code]...
View 1 Replies
Dec 9, 2010
I have a class Trans, with properties siteID and TID. I have a generic list of this class, TransList = list(Of Trans).
Now I want to find the Trans in TransList where the siteID is 3 and the TID is T1. There will only be one record. I want to then update this Trans in the TransList (so I need a reference to the Trans). I am trying to do the following, but it doesnt like it.
[Code]....
View 2 Replies
Aug 19, 2010
In Asp.net Web forms why must a user control be partial? I tried to remove the partial keyword and it says: Missing partial modifier on declaration of type 'test'; another partial declaration of this type exists
Where is the other declaration?I am trying to pass a generic type with the user control how can I do that? I can't unless I change the other declaration too. I couldn't find it so I removed the partial keyword.Note:
you do have 3 files if your making WebApplication but if your making website you only get 2 files?
UserControl.ascx
UserControl.ascx.cs
so in website where is the other declaration?the reason i want generic is because im making a Grid User Control so i want to pass the type the datasource is going to have.
View 4 Replies
Aug 19, 2010
I've had a bit of a problem trying to bind a generic list to a repeater. The type used in the generic list is actually a struct.
I've built a basic example below:
[code]....
I then create two fruits using the struct (apple and orange). These fruits are then added to the list.
Finally, I bind the generic list to the DataSource property of the repeater...
The markup looks like this:
[code]....
I expect to see the fruit name and price printed on the screen, separated by a horizontal rule.
At the moment I am getting an error relating to actual binding...
**Exception Details: System.Web.HttpException: DataBinding: '_Default+Fruit' does not contain a property with the name 'FruitName'.**
View 2 Replies
Dec 10, 2010
I'm busy writing a handler to serve various documents for download or presentation in web forms pages. The documents range from various image formats, to PDF, to MS Office documents, to generic binaries. My basic draft of the download process is as below:
[code]....
However, I have some misgivings about lumping all documents together as application/octet-stream, and I would prefer, if feasible, to use a more specific content type per document type. I have a DB table for document types where I could store this. Am I going in the right direction, and if so, where can I find a suitable starting list of content types for document types?
View 1 Replies
Dec 7, 2010
I'm writing a formbuilder for our CMS which dynamically loads bespoke controls into panels within a repeater.
The bespoke controls all inherit from, lets say 5arx.FormBuilder.FormControl, a base class which defines abstract methods for initialising, validating, repopulating, gathering submitted data from them. Controls range from simple text fields to complex, composite client-side controls.
It all works very well, but I've noticed something I feel is anomalous. During the course of writing code to retrieve form controls. gather their data and persist it to my database I noticed that their type reverts to the way objects get typed if you write your code in the (v. irritating) VS 'website project' mode.
So, for example a control that is defined as living in a namespace and being of type
5arx.FormBuilder.FormControl.MyBespokeControl
Sarx.FormBuilder.FormControl.MyBespokeControl
at runtime reports its type (via simple call to GetType()) as being of type:
ASP.5arx_FormBuilder_FormControl_MyBespokeControl
ASP.Sarx_FormBuilder_FormControl_MyBespokeControl
Getting the BaseType property will correctly retrieve the underlying class, but it is perplexing to me why this should be happening. Particularly as I spent much of the summer refactoring our app from its original form as VS Website project (complete with shared code in the App_Code folder and other nastiness) to the (IHMO) correct web application project + supporting claass libraries so that we would have control over our namespaces and not get everything compiled into the ASP.x namespace
EDIT: Modified the (hypothetical) example root namespace.
View 1 Replies
Apr 23, 2010
I have several custom classes that derive from a common base class so they share several members in common. I would like to be able to pass objecs from any of these three classes to a function that will "look at" common properties. However, it seems there is a catch 22 -- When I try to access a member (.FirstName) of the passed object, the computer reports an error that it thinks the member doesn't exist.
It seems to be a sort of contradiction -- since I didn't declare the type, the computer can't confirm existence, but it seems that it should have to take it on faith since the generic character of the type is specified by the code. Possibly there is something I don't know about that would fix this. I'm showing VB code for what I have so far. I went ahead and hardcoded an instance to confirm that the object exists and has the needed property. I commented out the line that had the code that resulted in the computer reporting an error.
[Code]....
View 2 Replies
Mar 8, 2010
I'm receiving this error in my Linq statement ---
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'hcgames.ObjectClasses.ShoppingCart.ShoppingCartCartAddon'. An explicit conversion exists (are you missing a cast?)
From this query
ShoppingCartItems items = Cart.GetAllItems();
ShoppingCartCartAddons addons = Cart.GetAllAddons();
var stuff = from x in items
select new ShoppingCartItem()
{
ProductID = x.ProductID,
Quantity = x.Quantity,
Name = x.Name,
Price = x.Price,
Weight = x.Weight,
Addons = (from y in addons
where y.ShoppingCartItemID == x.ID
select y)
};
View 2 Replies
Nov 30, 2010
I have a class constructor which accepts a Listbox.
[Code]....
I need to be able to pass another control type and execute the exact same logic in one of the methods... Seems like a use for Generics... I'm not so sure about the syntax... The type of control that I will pass is a rad combo box which has many of the same properties of the listBox control. However, RadComboBox does not inherit from listBox or dropDown so I am unable to cast. When changing the signature of the constructor to As RadComboBox as well as the property and field the method works as expected. I am trying to avoid duplicating code here.
View 1 Replies
Mar 14, 2011
[Code]....
[Code]....
The GetList method is as folllowing:
[Code]....
Now i can populate my gridview trough code by this: //gvwDiensten.DataSource = new BindingList<diensten>(dataManager.GetList<diensten>().ToList());But i would like to use an objectdatasource, so i created this:
[Code]....
</asp:ObjectDataSource>
But when running the page i get:
ObjectDataSource 'dsDiensten' could not find a non-generic method 'GetList' that has no parameters.
View 5 Replies
May 2, 2010
Calling Index view is giving me this very very annoying error . Can anybody tell me what to do about it
Error:The model item passed into the dictionary is of type 'System.Collections.Generic.List1[MvcApplication13.Models.Groups]', but this dictionary requires a model item of type 'MvcApplication13.Helpers.PaginatedList1[MvcApplication13.Models.Groups]'.
public ActionResult Index(int? page)
{
const int pageSize = 10; [code].....
View 1 Replies
Oct 1, 2010
Is something like the below possible?
public static T Sum<T>(this DataTable dt, string columnName)
where T : IEnumerable<decimal>, IComparable<decimal>[code]....
It feels like i'm almost there, but not quite :/
Just trying to sum up either decimal or int values in a column in datatable. Currently getting a compile error, however think this is due to the incorrect generic constraint.
View 3 Replies
Feb 5, 2010
I can have a base class for views in an MVC project like this:
public class BaseViewPage : System.Web.Mvc.ViewPage
{
public string Something { get; set; }
}
And then in the ASPX I can do this:
<%@ Page Something="foo" Language="C#" Inherits="MyNamespace.BaseViewPage" %>
This works fine; the problem is when I try to do the same with the generic version:
public class BaseViewPage<TModel> : System.Web.Mvc.ViewPage<TModel> where TModel : class
{
public string Something { get; set; }
}
When I try to use this from the ASPX, like this:
<%@ Page Something="foo" Language="C#" Inherits="MyNamespace.BaseViewPage<SomeClass>" %>
I get the error message:
Error parsing attribute 'something': Type 'System.Web.Mvc.ViewPage' does not have a public property named 'something'.
Notice how it tries to use System.Web.Mvc.ViewPage rather than my BaseViewPage class. To make it more interesting, if I remove the "Something" attribute from the Page directive and put some code in the generic version of BaseViewPage (OnInit for example) the class is actually called / used / instantiated.
So, am I doing something wrong or is this a limitation.
View 1 Replies
Apr 12, 2010
I'm trying to extend the GridView class to always show the header and footer even when the datasource is empty by using the code I found online (link). However, the code is written in C# but I use VB.
What is the VB equivalent of the following?
public event MustAddARowHandler MustAddARow;
Is there a way around VB.NET not allowing events to return a type?
Also, I cannot convert the following function because of the error below.
Code:
[code]....
View 3 Replies
Jul 26, 2010
I have a web service and its methods return a class which is name WSResult. WSResult has 2 properties. One of property's type is int and the other one's type is object. I want to return some different type with this second property.
[code]....
How can i pass an object which i retrieved from other web services or that i generated from my serializable classes inside M_ResultObject property ?
View 2 Replies
Jun 30, 2010
Do any one know how to return an anonymous type. I am using Linq where i need to return the following code
private <What's the return type to be provided here> SampleLinq(Int32 Num)
{
var query = (from dept in obj.DeptTable where dept.Id == Num select new { dept.DeptName, dept.DeptId });
return (query)
}
View 8 Replies