|
I almost lost some money today on a bet with a colleague arguing that the following Java code was just plain invalid.
if( this_thing == DING & that_thing == DONG ) {
thenGoDoTheOtherThing();
} Fortunately, he did not take me up on the bet! Turns out, for both Java and C#, when the & operator is used in this context the compiler stops treating it as the bitwise AND operator. Instead it treats it like the logical AND operator (&& ) except that it applies a slightly modified evaluation rule - where && stops evaluation as soon as it encounters the first expression that evaluates to false , & goes ahead and evaluates all the expressions regardless of what each component expression evaluates to. The logical AND still works as one might expect, just that all the component expressions are always evaluated. Here's an example:
class Program
{
static void Main(string[] args)
{
if (Eval1() & Eval2())
Console.WriteLine("Eval1() and Eval2() returned true.");
else
Console.WriteLine("Eval1() and/or Eval2() returned false.");
}
static bool Eval1()
{
Console.WriteLine("Eval1");
return false;
}
static bool Eval2()
{
Console.WriteLine("Eval2");
return true;
}
} And here's the output you get.
Eval1
Eval2
Eval1() and/or Eval2() returned false. Guess you learn something new everyday! I am not sure that using this feature is such a great idea though. Thoughts?
modified on Friday, December 4, 2009 3:31 PM
|
|
|
|
|
IMO, that it doesn't do the short circuit evaluation means that it actually is a bitwise AND, between two bools, but that doesn't make it any less "bitwise" or "AND", a bool is just 0 or 1 with nicer names after all..
|
|
|
|
|
Yep, it does indeed still do a bitwise AND of the boolean operands. See my reply[^] to OriginalGriff[^]'s post below.
|
|
|
|
|
Fortunately it should only work if (as in your example) both the parameters are bool - as it then performs a bitwise AND of the two results. Hence why it evaluates both rather than stopping when one fails.
It's still quite nasty though - I wonder if you can turn it off...
if ((dataTable.Rows != null) & (dataTable.Rows.Count > 0))
{
...
} would throw exactly the exception you are testing to avoid!
No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced.
This message is made of fully recyclable Zeros and Ones
"Rumour has it that if you play Microsoft CDs backwards you will hear Satanic messages.Worse still, is that if you play them forwards they will install Windows"
|
|
|
|
|
Yes. It does still perform a bitwise AND of the 2 boolean operands. Here's the IL for the sample code:
L_0000: call bool ConsoleApplication1.Program::Eval1()
L_0005: call bool ConsoleApplication1.Program::Eval2()
L_000a: and
L_000b: brfalse.s L_0018
L_000d: ldstr "Eval1() and Eval2() returned true."
L_0012: call void [mscorlib]System.Console::WriteLine(string)
L_0017: ret
L_0018: ldstr "Eval1() and/or Eval2() returned false."
L_001d: call void [mscorlib]System.Console::WriteLine(string)
L_0022: ret And I agree, it does seem to be a fairly dangerous operator. I'd be surprised if somebody deliberately used it with this explicit intent - chances are, in a majority of the cases its occurrence is a typo - and something the compiler won't even alert you about.
|
|
|
|
|
That is what the documentation says:
"Binary & operators are predefined for the integral types and bool. For integral types, & computes the logical bitwise AND of its operands. For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true.
The & operator evaluates both operators regardless of the first one's value."
And now you can go and test/read up on the | operator...
|
|
|
|
|
Luc Pattyn wrote: And now you can go and test/read up on the | operator...
What about ^ ? One of the most underestimated operators ever.. except in cryptography of course.
On the other hand, I've never had to xor two bools together, I've only done it once and just for laughs
|
|
|
|
|
XORing bools isn't very useful for two bools, as you could as well compare them for (in)equality; XORing multiple bools makes more sense, not too many application domains will ever need it though.
However XOR is fundamentally different from AND and OR, as there is no ^^ operator, and no short-circuiting.
|
|
|
|
|
Luc Pattyn wrote: However XOR is fundamentally different from AND and OR, as there is no ^^ operator, and no short-circuiting.
Well of course not, that would be impossible, the result always depends on both inputs
|
|
|
|
|
Exactly, it isn't "destructive", it preserves the true (or false) probability, something AND and OR don't.
|
|
|
|
|
Just in the same way, we could use | or || for normal or "short circuit" OR.
|
|
|
|
|
Dear Sirs,
I would like to learn how to create Visual Studio (2008) addins. I thought I would start by making one that changes the color of the current line. This has proved to be very difficult. First, there are very few examples, so I go to the SDK. Second, it seems that the MSDN isn't consistent here. I don't know what I'm missing, but I see
DTE.get_Properties(String category, String page); in code, but DTE properties[^] lists it differently, as
DTE.Properties {get;} Whatever, I got past that, and now I use get_Properties(string, string) . So, I found out how to get general color properties:
Properties ps = DTE.get_Properties("FontsAndColors", "TextEditor");
Property fC = ps.Item("FontsAndColorsItems");
FontsAndColorsItems fcs = fC.Object as FontsAndColorsItems;
foreach (ColorableItems a in fcs)
Debug.WriteLine(a.Name); (the above listing gives all the different properties in Tools > Options > Environment > Fonts and Colors > Display items: )
****GETTING TO THE POINT****
But, what I need is to be able to access LOCAL color properties. A start might be to be able to set the font color or background color, or whatever, of the current selection:
Document doc = DTE.ActiveDocument;
TextSelection sel = doc.Selection as TextSelection;
Or something like that. Any suggestions?
In Christ,
Aaron Laws
http://ProCure.com
|
|
|
|
|
Maybe the way to do it is by painting on the code window with alpha colors???
get the top point and the bottom point, and paint the following color onto the code window between those points for the width of the form:
255,255,255,200
(r,g,b,a)??
In Christ,
Aaron Laws
http://ProCure.com
|
|
|
|
|
hey ,
I have a tabcontrol which contain only images and no text in the tabs. I want to have a TabHover and a different image when the tab get selected. Rite now i am using an imagelist to put images in the tabs.
Please guide me through it.
I tried the event on TabHover but was not successful.
Thanks
Sushant kaura
sushant kaura
|
|
|
|
|
I have a simple class (just contains automatic properties, nothing special), and a Form w/ a datagridview on it. It is binding directly to the class, and is working fine in every respect, however I want to autosize the columns to the data within them after bind (but retain it's current column sizing mode of 'None' afterwords so the user can resize them)
I call AutoResizeColumns and pass DataGridViewAutoSizeColumnsMode.DisplayedCells
(I've also tried 'AllCells'). The datagrid doesn't resize though! Am I missing something?
private void PopulateUI() {
this.dataGridViewHistory.AutoGenerateColumns = false;
this.dataGridViewHistory.DataSource = this.Project.Modifications;
this.dataGridViewHistory.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.DisplayedCells );
}
this.dataGridViewHistory.AllowUserToAddRows = false;
this.dataGridViewHistory.AllowUserToDeleteRows = false;
this.dataGridViewHistory.AllowUserToOrderColumns = true;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.PapayaWhip;
this.dataGridViewHistory.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridViewHistory.ColumnHeadersHeightSizeMode =
System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewHistory.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnUserID,
this.ColumnUserName,
this.ColumnDate,
this.ColumnFileName} );
this.dataGridViewHistory.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridViewHistory.Location = new System.Drawing.Point( 6, 16 );
this.dataGridViewHistory.Name = "dataGridViewHistory";
this.dataGridViewHistory.ReadOnly = true;
this.dataGridViewHistory.RowHeadersVisible = false;
this.dataGridViewHistory.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridViewHistory.Size = new System.Drawing.Size( 550, 236 );
this.dataGridViewHistory.TabIndex = 0;
|
|
|
|
|
Hi all,
I am trying to combine two datatables into single datatable...
First table contains 3 columns[e.g: 'col1','col2','col3']
Second table contains 2 columns[e.g: 'col4','col5']
Both tables have the same no.of records[rows], but different columns.
How to combine them into single table?
I need DataTable with columns ['col1','col2','col3','col4','col5'].
I am inserting through looping the both the tables and adding values into third table.
I tried the Merge (DataTable.Merge()), but it is adding the records to bottom of first one, but i need it should be added to the side[as columns] to first table'
Is there any other way? please suggest me.
Thanks in advance.
|
|
|
|
|
sekhar.k wrote: I am inserting through looping the both the tables and adding values into third table.
That should work. But a better technique is to use a join in your SQL query to start with.
|
|
|
|
|
Is there a common key column between these two tables?
|
|
|
|
|
Thanks for your response.
There is no common key or relation ship between them.
Both queries are from different tables.
|
|
|
|
|
Then joining them may not make any meaning since the order of rows returned by SQL Server is not guaranteed. If you still want to proceed, add an IDENTITY column to both tables and use those columns to join the tables.
|
|
|
|
|
I cannot seem to get this working correctly. I did get it to work once but after I compiled it again it stopped. I am using the code from Scratchpad/Signature Capture as BMP on Pocket PC[^].
The strange thing is when I save it, it saves just a white background with no writing. It will let you draw on the screen but it doesn't save what you are drawing. I have posted to that article with no reply as of it but I just cannot seem to figure out why it would be doing this?
It is kind of difficult for me since it isn't using the System.Drawing framework from the latest version.
I have coded it exactly like he has it:
private string AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
private Signature cSignature;
public Sig()
{
InitializeComponent();
cSignature = new Signature();
cSignature.Location = pnlSig.Location;
cSignature.Size = pnlSig.Size;
this.Controls.Add(cSignature);
}
private void Sig_Load(object sender, EventArgs e)
{
cSignature.SetPenColor(Color.Black);
if (File.Exists(Path.Combine(AppPath, "CapturedSignature1.bmp")))
{
DialogResult result = MessageBox.Show("There is a signature that exist.\nWould you like to open it?", "Open?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
cSignature.LoadImage(Path.Combine(AppPath, "CapturedSignature1.bmp"));
}
}
}
private void menuItem1_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
cSignature.Save(Path.Combine(AppPath, "CapturedSignature1.bmp"));
Cursor.Current = Cursors.Default;
}
Does anyone else have possibly another idea or another class I could use?
|
|
|
|
|
I actually had to copy the programmers designer code of the form and use it to make it work... weird...
|
|
|
|
|
Can any one Help,
I am trying to do following step dynamically using UIAutomation
in c# 3.0
1)Open Outlook
2)Open Inbox
3)Select first unread email.
4)Open the first unread email.
5)If there are attachements, download the attachements.
Select next unread email and do the same as above.
I have tried below code.I Can open the outlook Express.But I can't read mail.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Automation;
using System.Diagnostics;
namespace ConsoleApplicationUI
{
public class ReadMail
{
static void Main(string[] args)
{
ProcessStartInfo psInfo = new ProcessStartInfo(@"C:\Program Files\Outlook Express\msimn.exe");
Process prov = Process.Start(psInfo);
Thread.Sleep(5000);
AutomationElement Inboxstart = null;
PropertyCondition Inboxconds = new PropertyCondition(AutomationElement.NameProperty, "Inbox");
Inboxstart = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, Inboxconds);
if (Inboxstart != null)
{
InvokePattern InboxstartInvoke = (InvokePattern)Inboxstart.GetCurrentPattern(InvokePattern.Pattern);
InboxstartInvoke.Invoke();
}
Console.Read();
}
}
}
Thanks,
Bruze
|
|
|
|
|
Good day folks,
I am searching for a specific website, it displays some useful information for me, however, the information is too much and they are not presenting them in a convenient way. Basically the search result is displayed in a grid type control (most likely gridview), I need to click each page number to see all the content if it is not on first page.
So I am wondering if I can do something to save my time? I want to write a httpwebrequest to retrieve the search result and save to local for analysis, that way I need to know how can I let my program to automatically "click" on the page number and get the result on that clicked page.
Can anyone point out some direction for me?
Thank you very much in advance. Any hint is greatly appreciated, currently this is very inconvenient and is costing me too much time every day
|
|
|
|
|
hi, you need to know the parameters send by the page 3 click than you can redirect using the new http request for page 3
i think that would be one way
|
|
|
|
|