|
|
i have a cusotmer class that contains some attributes like
public class dummy {
public string name {get; set;}
public string value {get; set;}
public dummy(string name, string value = string.empty)
{
this.name = name;
this.value = value;
}
public static implicit operator dummy(string value)
{
stackframe?
return new dummy();
}
}
in other modules, has some codes
dummy _foo = new dummy("Json");
_foo = "Hello";
question is: can i get the _foo object in implicit operator method? so i can keep "Json"
attribute, thanks for advance
|
|
|
|
|
Jon Skeet: "Custom conversions are only very occasionally useful, just like user-defined operators."
Yes, you can do this:
public static implicit operator dummy(string value)
{
return new dummy("????", value);
} And now you have a way to create a new instance of the Class 'dummy with the optional string parameter 'value defined: but, what does that really do for you ? Your intention in designing the code was to require a 'name parameter, and now you have a 'dummy with "????" for a name: is that useful ?
This is just duplicating (poorly) using the regular public dynamic Class constructor, and this is not what 'implicit is meant to be used for, which is user-defined conversion facilities that make it easy to write code that does not require explicit casting.
imho, using the 'implicit keyword to just short-cut some aspect of constructing a new instance of a Class is a very bad "code-smell."
'implicit methods must be static, as you know; that means there can be one-and-only one "instance" of the method which is a method of the Type of the Class, not of instances of the Class.
That means that inside an 'implicit method you have no ability to "know" what the current instance of the Class in which the 'implicit method was called from is: the keyword 'this is not available.
Since you can pass only one parameter into an 'implicit method, you can't pass both a reference to an instance of the Class, and some value (in this case a string) that you want to use (in this case to assign to an internal field in the Class).
So, why not just do the "easy" thing when you want to assign to your 'value field:
dummy _foo = new dummy("Json");
_foo.value = "Hello"; By the way: in your Class' constructor:
public dummy(string name, string value = string.empty) is incorrect: spelling error.
And if you used: public dummy(string name, string value = string.Empty) that would throw a compile error: optional parameters need to have compile-time constant initial values. This would work:
public dummy(string name, string value = "")
... or ...
public dummy(string name, string value = default(string))
“I speak in a poem of the ancient food of heroes: humiliation, unhappiness, discord. Those things are given to us to transform, so that we may make from the miserable circumstances of our lives things that are eternal, or aspire to be so.” Jorge Luis Borges
modified 17-Apr-14 0:34am.
|
|
|
|
|
Thanks BillWoodruff
but class dummy just dummy the main point is when
dummy _foo = new dummy("Json");
_foo.value = "Hello";
can i get _foo object in implicit operator method?
|
|
|
|
|
Thanks BillWoodruff
Yes, you can do this:
public static implicit operator dummy(string value)
{
return new dummy("????", value);
}
And now you have a way to create a new instance of the Class 'dummy with the optional string parameter 'value defined: but, what does that really do for you ? Your intention in designing the code was to require a 'name parameter, and now you have a 'dummy with "????" for a name: is that useful ?
sample dummy is simple, only has one attribute : name, real class have maybe hundreds attributes or even more and some of these attributes are private, so can't use attributes set, and use other functions like _foo.setValue("Hello") is not allowed
|
|
|
|
|
Clear, clean, object-oriented design is an art and skill that takes time to develop.
Fields, and Properties, of Classes should be designed to clearly express the intent of the program, and the structure of flow-of-control.
Use Private/Public Fields, and Public Properties for specific, carefully chosen, reasons. Usually you make a Field (a variable of some Type) private because you don't want it exposed to change outside the Class it is defined in.
Similarly, you may define a Property with a private set, and a public get, to allow all consumers of instances of the Class to get the value of the Property, but only code inside the context/scope of the Class in which the Property is defined to set/change the value.
Anytime you design a Class with "hundreds of attributes," I think there's a good chance that the Class needs to re-designed, possibly decomposed into a set of inter-related smaller Classes.
I think you are kind of off-track here in exploring this type of use of the 'implicit operator.
good luck, Bill
“I speak in a poem of the ancient food of heroes: humiliation, unhappiness, discord. Those things are given to us to transform, so that we may make from the miserable circumstances of our lives things that are eternal, or aspire to be so.” Jorge Luis Borges
|
|
|
|
|
uh shame on me
i looked through my question:
sample is wrong,correct code is:
dummy _foo = new dummy("Json");
_foo = "Hello"
so _foo's attribute name must be kept in new dummy from implicit operator
thanks for advanced
|
|
|
|
|
I was wondering if there was a simple way to do a conversion from a typed list of type A that implements interface B, to a list of interface B. For the time being, I'm using an extension to do this, but I think it might be hard to understand by a novice developer who might review my code later on. Here is what I have:
So wondering, if anyone could simplify it a bit?
public static List<InterfaceType> ConvertClassItemToInterfaceItem<InterfaceType, ClassType>(this List<ClassType> originalist) where ClassType : InterfaceType
{
List<InterfaceType> list = new List<InterfaceType>();
foreach(ClassType value in originalist)
{
InterfaceType itype = value;
list.Add(itype);
}
return list;
}
Edited to give example on how to use extension method:
interface B{}
class A : B{}
class C{
List Test()
{
List<A> list = new List<A>;
return list.ConvertClassItemToInterfaceItem<B,A>()
}
}
modified 16-Apr-14 13:20pm.
|
|
|
|
|
There is no need to convert it.
interface IA
{
void Test();
}
class AImpl : IA
{
#region IA Members
public void Test()
{
}
#endregion
}
List<AImpl> lst = new List<AImpl>();
lst.Add(new AImpl());
IA ib = lst[0];
That works just fine.
If you are dead set on converting, you can just do:
List<IA> lst2 = new List<IA>(lst);
|
|
|
|
|
Your first example, shows how to assign a variable of type A to a variable of type B, not List of type A to List of type B.
But your second example was exactly what I needed, thanks.
|
|
|
|
|
Another option would be:
List<Thingy> source = GetTheListOfThings();
List<IAmTheInterface> result = source.Cast<IAmTheInterface>().ToList();
If you're using .NET 4.0 and you're passing the list to a method that only uses the list in a foreach loop, consider making the parameter IEnumerable<IAmTheInterface> ; that way, thanks to generic interface covariance, you can just pass the List<TheClass> to the method directly.
If you need access to the Count property, or read-only access to the indexer, and you're using .NET 4.5, consider using the IReadOnlyList<T> [^] or IReadOnlyCollection<T> [^] interfaces. These will also allow you to pass the source list to the method directly.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Simplified class structure:
interface InterfaceA
{
List<InterfaceC> D{get;};
}
interface InterfaceC
{
}
class ClassE : InterfaceA
{
List<InterfaceC> PropertyD
{
get
{
return new List<InterfaceC>(MethodThatReturnsListOfTypeClassF());
}
}
class ClassF : InterfaceC
{
}
If you have a better idea on how to do it, I'm all ears, though I think this approach will do just fine.
|
|
|
|
|
It really depends on how you're using the list returned from InterfaceA.D , and how painful it would be to change the type.
Assuming you're not writing to the returned list, and you're using .NET 4.5, then this might be simpler:
interface InterfaceA
{
IReadOnlyList<InterfaceC> D { get; }
}
class ClassE : InterfaceA
{
public IReadOnlyList<InterfaceC> D
{
get { return MethodThatReturnsListOfTypeClassF(); }
}
}
If you're only using the value in a foreach loop, or passing it to methods which take an IEnumerable<T> , then you can make the property type IEnumerable<InterfaceC> , which will work in .NET 4.0 or higher:
interface InterfaceA
{
IEnumerable<InterfaceC> D { get; }
}
class ClassE : InterfaceA
{
public IEnumerable<InterfaceC> D
{
get { return MethodThatReturnsListOfTypeClassF(); }
}
}
Otherwise, it's a purely aesthetic choice between:
new List<InterfaceC>(MethodThatReturnsListOfTypeClassF()) MethodThatReturnsListOfTypeClassF().Cast<InterfaceC>().ToList() MethodThatReturnsListOfTypeClassF().ToList<InterfaceC>()
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I haven't decided yet on the exact implementation, but it's likely to be the following:
- add items to the list or add the items directly into the database, depending on what I feel is best
- display the list on a webpage, possibly using paging depending on the number of items in that list. I have no idea at the moment whether it will be a few items or a few dozen.
What are the advantages of using a readonly collection class? I assume it's slightly faster, but otherwise I have no idea of what it implicates.
Side info:
I've only written the data access layer of my program so far. Very soon starting on user interface.
Having said that, I've already got the implementation to insert items directly into the database and have no collection class that supports inserting, deleting or modifying items in that list yet.
My fellow team members haven't started coding yet, so I can still easily change the type to IEnumerable.
I lead a team of 3 people to make a school project to make a small program for a client. My teacher told me and my team members that I should make a seperate data access layer, cause my code is too complicated for my team mates to understand, but end up making the same user interface(website). So need to have an interface so everything keeps working regardless which DAL we use. My team members have little experience with extension methods, generics and lambda expressions.
|
|
|
|
|
The main advantage of returning an IReadOnlyList<T> or IEnumerable<T> is that it makes it obvious that you can't change the list.
With your current implementation, the following code looks sensible:
InterfaceA theInstance = GetTheInstanceOfClassE();
theInstance.D.Add(new ClassF());
However, since the getter for property <c>D is returning a new List<T> every time you call it, any changes to the list will be discarded.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
As I said before, the code is a bit simplified, here is closer to the actual implementation.
private List<InterfaceType> listofitems;
public List<InterfaceType> ListOfItems
{
get {
if(listofitems==null)
{
listofitems= new List<InterfaceType>(ClassType.GetListOfTypeClassType(this.id));
}
return listofitems;
}
}
A readonly list, does it mean you can't change the list or the list AND its contents?
I think it's the latter, but I'm not sure. The list itself is pretty much already protected by not adding a setter for it.
|
|
|
|
|
If you expose it as an IReadOnlyList<T> , the caller won't be able to change the contents of the list.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
User Information I.e Profile information such as name ,dob etc filled by user during registration?
|
|
|
|
|
|
How to change Login button to logout after login in same page?
krishnendu Nandi
|
|
|
|
|
butLogin.Text = "Logout";
Then just check if he is logged in in the Click event handler and perform the appropriate action.
Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952)
Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)
|
|
|
|
|
Hi, I am hoping someone can help me with this. I need a program that counts char,vowels and words. I can get it to do all those things alone, but I am at a loss on how to make it all work together. Please help. Thanks!
This is the program to count char, it works fine.....
#include <stdio.h>
#include <string.h>
#define MAXNUM 1000
int countchar(char[]);
int main()
{
char message [MAXNUM];
int numchar;
printf("\nType in any number of characters : ");
gets(message);
numchar = countchar(message);
printf("\nThe number of characters is %d",numchar);
return 0;
}
int countchar(char list [])
{
int i, count = 0;
for(i=0; list[i] != '\0'; i++)
count++;
return(count);
}
This is the program to count vowels, it worked fine until i tried to add the char count.....
#include<stdio.h>
int main()
{
char str, line[150];
int i,v,c,ch,d,s,o,l, countchar, count, list;
o=v=c=ch=l=d=s=0;
printf("Enter a line of string:\n");
gets(line);
for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U')
++v;
}
{
int countchar(char list [])
int i, count = 0;
for(i=0; list[i] != '\0'; i++)
count++;
return(count);
}
printf("Vowels: %d",v);
printf("characters %d",countchar);
return 0;
}
|
|
|
|
|
And what, pray, does that have to do with C#?
Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952)
Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)
|
|
|
|
|
Your first problem is that this is C++ code and you have posted in the C# forum.
However ...
You should create all the separate functions to perform a specific action, and return the appropriate count. You then call each one from main passing the string to it. Something like:
int main()
{
int characterCount;
int vowelCount;
int digitCount;
char message [MAXNUM];
printf("\nType in any number of characters : ");
gets(message);
characterCount = CountCharacters(message);
vowelCount = CountVowels(message);
digitCount = CountDigits(message);
return 0;
}
Then you just have to write each function to do the counting and return the total.
|
|
|
|
|
This is supposed to be c code, I used my C book as the base of the code.Thanks for the tips. Can you help me with the counting? I think the problem I am running into is that I used i once for example when counting vowels and can not use it again when counting words. I'm really stuck here.
|
|
|
|
|