|
Bernhard Hiller wrote: that's not possible with properties, even when they have no explicit setter
That's not necessary when the property has no explicit setter. The backing field can't be accessed (except via reflection), and it's marked as readonly automatically.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I can't help thinking that these examples are better expressed with a public method, and private field:
internal object _field = null;
public object Field
{
get
{
return _field;
}
}
public void SetField(object ofield)
{
_field = ofield;
} imho, clearer intent, and greater 'separation of concerns,' is expressed this way.
But, also: why even use a Property unless there is a compelling reason to so; a reason like needing to throw an error when the value is null; a reason like needing PropertyChange notification.
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it. A few hundred years later another traveler despairing as myself, may mourn the disappearance of what I may have seen, but failed to see.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
Did you miss something Bill? Nowhere in your code SetField() is called!
your code is exactly the same as mine minus the crucial part, the one I wonder about, when/where/how SetField() is called!
My question was about (elegant) lazy initialisation after all!
modified 21-Oct-17 3:24am.
|
|
|
|
|
Super Lloyd wrote: Did you miss something Bill? Yeah Sorry about that ! cheers, mate ...
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it. A few hundred years later another traveler despairing as myself, may mourn the disappearance of what I may have seen, but failed to see.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
|
If I had seen this:
private List<DateTime> _someList = null;
public List<DateTime> SomeList
{
get
{
_someList = _someList ?? new List<DateTime>();
return _someList;
}
} My brain might not have missed your train.
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it. A few hundred years later another traveler despairing as myself, may mourn the disappearance of what I may have seen, but failed to see.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
There are good days and there are bad days.
And there are days every day!
|
|
|
|
|
Fine, which one of those 3 methods do you prefer? Or do you have another suggestion?
public object GetExpensiveAndNonNullObject()
{
if (expensiveObjectBasedOnPrivateState == null)
expensiveObjectBasedOnPrivateState = new object();
return expensiveObjectBasedOnPrivateState;
}
object expensiveObjectBasedOnPrivateState;
Or
public object GetExpensiveAndNonNullObject()
{
expensiveObjectBasedOnPrivateState = expensiveObjectBasedOnPrivateState ?? new object();
return expensiveObjectBasedOnPrivateState;
}
object expensiveObjectBasedOnPrivateState;
Or
public object GetExpensiveAndNonNullObject()
{
return expensiveObjectBasedOnPrivateState ?? (expensiveObjectBasedOnPrivateState = new object());
}
object expensiveObjectBasedOnPrivateState;
Or.. something else?
modified 21-Oct-17 3:22am.
|
|
|
|
|
Super Lloyd wrote: return field ?? (field = Create());
While this code line is so trivial that there's no risk of misunderstanding it, I try to avoid making use of the expression-character of an assignment.
Method 2 I dislike for the same reason as you. So it's Method 1 for me.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Sascha Lefèvre wrote: I try to avoid making use of the expression-character of an assignment. There is something about that usage that gives me a sense of "spooky action at a distance"
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it. A few hundred years later another traveler despairing as myself, may mourn the disappearance of what I may have seen, but failed to see.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
I am using a DataRow to get and set values (based on the manually typed data table from How to Manually Create a Typed DataTable[^]. The fields in the datarow can have different attributes that I would need to track, the main one being a maximum number of characters for some strings, but different versions have different lengths. I was trying to use Attributes to help with this, but I am stuck with how to be able to set/determine the 'version' when going through the attributes. I'd like to be able to set the version on the dataset as a whole and have the fields of the data row be able to use that to determine how to get values.
Here's how I setup my attribute class:
[AttributeUsage(AttributeTargets.Property, AllowMultiple =true)]
public class MaxLengthAttribute : Attribute
{
public string Version;
public int MaxLength;
public MaxLengthAttribute(string version, int max)
{
Version= version;
MaxLength = max;
}
} Here's what the data row looks like and how I am envisioning this would work.
public CustomerRow : DataRow
{
[MaxLength("1.0", 40)]
[MaxLength("2.0", 45)]
public string Name
{
get
{
if(base["Name"] == DBNull.Value) throw new NullException("Name is null.");
return ((TruncatedString)base["Name"]).Value;
}
}
} I created a class called TruncatedString that has a string and bool, which i am using as the data type for the field in the data row. In the TruncatedString I am trying to get the version of the data set and the max length attribute to find out how long my field can be:
public class TruncatedString
{
public bool AutoTruncate;
private string _Value;
public string Value
{
get
{
if(AutoTruncate)
{
int maxLength = ???
if(maxLength >= 0 && Value.Length > maxLength) return _Value.Substring(0, maxLength);
}
return _Value;
}
set { _Value = value; }
}
}
I am not sure if Attributes are the best way to go with this setup, but I do need to be able to store the untruncated string as well as a way to get the truncated but be able to have different lengths for different versions. I also want to be able to do other attributes, for example a field that was added in version 2.0 but not available in 1.0.
|
|
|
|
|
Preprocessor and compiler directives are one way of accomplishing what you want:
#if (C# Reference) | Microsoft Docs
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Few days back, I went for an interview. They just asked me to write code for reversing the array without using Array.Reverse() method. So, here I am sharing the code that might help someone.
for (int i=0; i<arr.Length / 2; i++)
{
int temp = arr[i];
arr[i] = arr[arr.Length – i – 1];
arr[arr.Length – i – 1] = temp;
}
Please let me know if there's any other way to do this. Thanks
|
|
|
|
|
Another way is to decompile the System-assembly which contains the method and copy that implementation into a new method to make up for the missing Array.Reverse() method. Alternative, I would use Enumerable.Reverse as an array is just another enumerable.
No, not the answer the interviewer is wanting, but correct nonetheless and the answer is at least equally valuable as the question
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Eddy Vluggen wrote: decompile the System-assembly
Or just go directly to the source code: Reference Source[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello,
Here is my problem: I am developping a game engine in C # (Winform). The program icon is correctly managed. I want to modify this icon, once the program launched, dynamically, to reflect the choice of the game that has just taken place. The process is done correctly, EXCEPT that it only works if the executable has been launched directly. On the other hand, if the launch was made from a shortcut, (choice in the Start Menu, for example, or redirection icon on the desktop), the icon in the taskbar remains obstinately blocked on the program icon. I tested this program under XP, where it reacts to my convenience (dynamic change of the correct icon) and under W7 or W10 where the update of this icon does not happen.
Here is the code that I use for this function:
try
{
Bitmap b = null;
b = new Bitmap (Fen.Chm + Fen.Gam + "\\" + f);
IntPtr p = b.GetHicon ();
Icon = Icon.FromHandle (p);
b.Dispose ();
}
catch (Exception x)
{
MessageBox.Show (x.Message);
}
I could not find the solution on any site I visited. Does anyone have a track?
|
|
|
|
|
i need a concept that i want to develop a winform apps which will be running as invisible apps in windows OS. when some one try to stop this apps from task manager then a password dialog box will appear. if user could provide right password then apps will be stored or otherwise apps will not be stopped.
please share the idea to show dialog box when user try to stop my apps from task manager.
|
|
|
|
|
MyDialogForm mf = new MyDialogForm();
if (mf.ShowDialog() == DialogResult.OK)
{
string input - mf.UserInputString;
...
}
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
modified 16-Oct-17 14:19pm.
|
|
|
|
|
Sounds like a great way to get your application classified as "malware".
If you control the computer, then write a Windows service. Only users in the local Administrators group will be able to stop it.
If you don't control the computer, then you have no right to prevent the user from terminating your application. After all, it's their computer, not yours.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
(Not a question, not a Tip/Trick in my eyes. Wanted to share and didn't see a better place for it.)
I'm implementing a write-ahead log (WAL) for an application and was searching for an answer on how to make sure a file actually gets written to disk when I close the FileStream and doesn't linger in one of the intermediary I/O caches, being vulnerable to system power loss.
There's a lot of confusion "in the webs" about which way is actually working:
- FileOptions.WriteThrough / FILE_FLAG_WRITE_THROUGH
- FileStream.Flush(flushToDisk: true)
- Win32.FlushFileBuffers
I was about to ask here when I finally found this:
Revised notes on the reliability of FlushFileBuffers – The Old New Thing[^]
tl;dr: FlushFileBuffers is the way to go on Windows 8 and newer (also best bet on Win7), FileOptions.WriteThrough might work as well but probably not, blame the storage device manufacturers.
Looking into the source of FileStream (.NET 4.7) I saw that all FileStream.Flush(flushToDisk: true) actually does is to call Win32.FlushFileBuffers. On my Google journey I found "hints" that this might not always have been the case, so if you need it, you should look into the source of the .NET version you're using.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
hi,
how can i add voipsdk.dll to reference? i can't find it where the ozeki voip sdk has been installed
|
|
|
|
|
Try reinstalling the SDK, but this time pay attention to where it goes.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
I have a class named train ...it has members like train no,trainname etc...i want to create instances of the class at runtime...for each instance new task has to be created and started....
Please guide me to start individual task for each instances when they are created dynamically.
|
|
|
|
|
In your class constructor, add a thread.
The simplest way to do that is to use the BackgroundWorker Class (System.ComponentModel)[^] as it provides a simpel mechanism for communicating with the original thread if necessary.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|